代码之家  ›  专栏  ›  技术社区  ›  JadedEric

泛型模板类的c#反思

  •  1
  • JadedEric  · 技术社区  · 14 年前

    下面是我的代码示例:

    public abstract class<T>
    {
       public List<T> GetSomething(string q)
       {
          **List<T> list = new List<T>();**
    
          Type type = typeof(T);
          PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance);
    
          foreach (PropertyInfo info in props)
          {
              // at this point I need to return information from a data source query
              // and build the members (set values) according to the returning results
              // which needs to be added to a list that contains T with each property
              // within set to a value. "Some Value" should be an object instance required
              // by the Type of the PropertyInfo.
    
              info.SetValue(type, "Some Value", null);
              **list.Add(type);**
          }
       }
    
       **return list;**
    }
    

    信息设置值由于模板类型的原因,(object,object,object[])不可访问,对吗?我在这里的问题是,如何在T中包含的属性上设置值?

    编辑:这个问题连我自己都搞糊涂了。我已经修改了上述程序,以代表我的直接需要。

    谢谢, 埃里克

    2 回复  |  直到 14 年前
        1
  •  2
  •   x0n    14 年前

    我看不出这有什么意义。你想在一个 但您正在通过 typeof(T) -a -至 PropertyInfo.SetValue

    public abstract class Foo<T> 
    { 
       public List<T> GetSomethingFrom(T instance) 
       { 
          Type type = typeof(T); 
          PropertyInfo[] props = type.GetProperties(BindingFlags.Public |
               BindingFlags.IgnoreCase | BindingFlags.Instance); 
    
          foreach (PropertyInfo info in props) 
          { 
              info.SetValue(instance, "Some Value", null); 
          } 
       } 
    } 
    

    -奥辛

        2
  •  0
  •   MarkPflug    14 年前

    最好断言您正在设置的属性实际上也是字符串,或者您对SetValue的调用(instance,“Some Value”,null)将抛出。

    似乎您正在尝试创建泛型对象初始值设定项。反思会起作用,但我建议调查系统.Linq.Expressions命名空间。您可以使用反射来构建LambdaExpression,您可以动态地将其编译成一个方法,该方法的性能将比每次使用反射初始化对象要好得多。