У меня есть следующий метод расширения:
public static class ListExtensions
{
public static IList AddRangeByKey(
this IList list, string keyName,
IEnumerable arrayElements) =>
list.AddRange(keyName, arrayElements);
// the other code is omitted for the brevity
}
Я хочу вызвать указанный выше метод расширения через отражение, потому что я не знаю T. Похоже, мы можем просто использовать отражение:
public static class UrlHelper
{
public static IEnumerable ToKeyValuePairs(
this object obj)
{
List keyValuePairs = new();
IEnumerable
props = obj.GetType().GetProperties()
.Where(p => p.GetValue(obj, null) != null);
foreach (PropertyInfo p in props)
{
object value = p.GetValue(obj, null);
IEnumerable enumerable = value as IEnumerable;
if (enumerable != null)
{
MethodInfo addRangeDef = typeof(ListExtensions).GetMethods()
.Where(x => x.Name == "AddRangeByKey" && x.IsGenericMethod)
.FirstOrDefault();
Type ienumerable = value.GetType()
.GetInterface("System.Collections.Generic.IEnumerable`1");
if (ienumerable != null)
{
MethodInfo addRange = addRangeDef
.MakeGenericMethod(ienumerable.GetGenericArguments());
addRange.Invoke(null, new object[] { p.Name, value }); // this
// line of code throws an exception 'addRange.Invoke(null, new
// object[] { p.Name, value })' threw an exception of type
// 'System.Reflection.TargetParameterCountException'.
// Message says `Parameter count mismatch`.
// I tried already like this:
// adRangeDef.Invoke(null, new object[] {
// typeof(UrlHelper), p.Name, value });
}
}
}
return keyValuePairs;
}
}
Код, который я пытаюсь запустить, выглядит следующим образом:
object queryObject = new SearchUsers
{
Page = 1, PageSize = 10,
Filters = new List{new FilterParameter {
Field = "name",
Val = "Bob" } }
};
IEnumerable foo = queryObject.ToKeyValuePairs();
Итак, эта строка кода addRange.Invoke(null, new object[] { p.Name, value }) выдает исключение:
'addRange.Invoke(null, new object[] { p.Name, value })' threw
an exception of type
'System.Reflection.TargetParameterCountException'.
Message says `Parameter count mismatch`.`
Я тоже пробовал звонить так:
addRangeDef.Invoke(null, new object[] { p.Name, value })
Но исключение было выброшено вот так:
Late bound operations cannot be performed on types or
methods for which ContainsGenericParameters is true.
Подробнее здесь: https://stackoverflow.com/questions/797 ... ion-method
Как запустить метод расширения через отражение от другого метода расширения? ⇐ C#
Место общения программистов C#
1761146434
Anonymous
У меня есть следующий метод расширения:
public static class ListExtensions
{
public static IList AddRangeByKey(
this IList list, string keyName,
IEnumerable arrayElements) =>
list.AddRange(keyName, arrayElements);
// the other code is omitted for the brevity
}
Я хочу вызвать указанный выше метод расширения через отражение, потому что я не знаю T. Похоже, мы можем просто использовать отражение:
public static class UrlHelper
{
public static IEnumerable ToKeyValuePairs(
this object obj)
{
List keyValuePairs = new();
IEnumerable
props = obj.GetType().GetProperties()
.Where(p => p.GetValue(obj, null) != null);
foreach (PropertyInfo p in props)
{
object value = p.GetValue(obj, null);
IEnumerable enumerable = value as IEnumerable;
if (enumerable != null)
{
MethodInfo addRangeDef = typeof(ListExtensions).GetMethods()
.Where(x => x.Name == "AddRangeByKey" && x.IsGenericMethod)
.FirstOrDefault();
Type ienumerable = value.GetType()
.GetInterface("System.Collections.Generic.IEnumerable`1");
if (ienumerable != null)
{
MethodInfo addRange = addRangeDef
.MakeGenericMethod(ienumerable.GetGenericArguments());
addRange.Invoke(null, new object[] { p.Name, value }); // this
// line of code throws an exception 'addRange.Invoke(null, new
// object[] { p.Name, value })' threw an exception of type
// 'System.Reflection.TargetParameterCountException'.
// Message says `Parameter count mismatch`.
// I tried already like this:
// adRangeDef.Invoke(null, new object[] {
// typeof(UrlHelper), p.Name, value });
}
}
}
return keyValuePairs;
}
}
Код, который я пытаюсь запустить, выглядит следующим образом:
object queryObject = new SearchUsers
{
Page = 1, PageSize = 10,
Filters = new List{new FilterParameter {
Field = "name",
Val = "Bob" } }
};
IEnumerable foo = queryObject.ToKeyValuePairs();
Итак, эта строка кода addRange.Invoke(null, new object[] { p.Name, value }) выдает исключение:
'addRange.Invoke(null, new object[] { p.Name, value })' threw
an exception of type
'System.Reflection.TargetParameterCountException'.
Message says `Parameter count mismatch`.`
Я тоже пробовал звонить так:
addRangeDef.Invoke(null, new object[] { p.Name, value })
Но исключение было выброшено вот так:
Late bound operations cannot be performed on types or
methods for which ContainsGenericParameters is true.
Подробнее здесь: [url]https://stackoverflow.com/questions/79796947/how-to-run-extension-method-via-reflection-from-another-extension-method[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия