得到List< T>具有后期绑定的值

本文关键字:绑定 List 得到 | 更新日期: 2023-09-27 18:07:57

我有一个List<T>变量,其中T在编译时不知道。我需要像这样访问类型Tvalue属性

foreach(var item in items) // items is List<T>
{
    item.value // this won't compile because T is unknown 
}

我知道<T>在我的情况下将具有value属性。我如何访问它?

得到List< T>具有后期绑定的值

如果您知道每个T都有您可以使用dynamic而不是var

foreach(dynamic item in items) //items is List<T>
{
    item.VALUE
}

正如已经回答的那样,正确的方法是创建一个实现Value prop的接口。

但是你已经说过你不能控制类,你需要用另一种方法来实现。

一种方法是反射,我假设你的属性名是VALUE,(区分大小写)
PropertyInfo pi = typeof(T).GetProperty("VALUE");
object value = pi == null ? null pi.GetValue(item,null);

您可以将反射调用缓存到一个静态泛型类中,该类在第一次使用时创建一个静态字段。

或者,您可以使用带有字段和helper方法的静态泛型helper类。

 public static class ValueHelper<T> {
     public static Func<T,object> ValueFunction;
     public static object GetValue(T item) {
        var function = ValueFunction;
        return function == null ? null : function(item);
     }
     }
 }

然后在代码的某个地方,你知道T,例如你想设置MyClass

  ValueHelper<MyClass>.ValueFunction = x => x.Value;

那么你的列表代码变成

foreach(var item in items)
{
    value = ValueHelper<T>.GetValue(item);
}

如果你可以控制T类,你可以引入一个带有Value属性的接口,并让每个T类实现这个接口。在这种情况下,您可以像这样枚举列表值:

    foreach(IMyInterface item in items)
    {
        var someVar = item.VALUE; 
//you know that item does have VALUE property and the type of that property as declared in interface
    }

乌利希期刊指南。即使你的T类有不同的属性,它也能工作:

interface IMyInterface
{
    string VALUE{get;set;}
}
class A : IMyInterface
{
   public int Aprop{get;set;}
   public string VALUE{get;set;}
}
class B : IMyInterface
{
   public int Bprop{get;set;}
   public string VALUE{get;set;}
}

如果提前知道T类型,那么您可以这样做(不是最好的方法,但这些已经在其他答案中解释过了):

foreach(var item in List<T>)
{
  if (item.GetType().Equals(typeof(fooClassA)))
  {
     ret = (item as fooClassA).VALUE_A;
  }
  if (item.GetType().Equals(typeof(fooClassB)))
  {
     ret = (item as fooClassB).VALUE_B;
  }
  ....
}
相关文章: