开发者

c# reflection on generic template class

Following a sample of my code:

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;**
}

info.SetValue(object, object, object[]) is not accessib开发者_开发百科le, due to the template type, correct? My question here would be, how can I set a value on a property, contained within T?

Edit: The question confused even myself. I've amended the procedure above to represent my direct needs.

Thanks, Eric


I can't see how this makes any sense. You're trying to set a property on an instance of T (as shown by your bindingflags,) but you are passing typeof(T) - a Type - to PropertyInfo.SetValue as the first argument. Perhaps you mean:

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); 
      } 
   } 
} 

In this case, we're passing an instance of T to the GetSomethingFrom method, then passing instance to SetValue. Follow?

-Oisin


It would probably be a good idea to assert that the properties you are setting are actually strings as well or your call to SetValue(instance, "Some Value", null) will throw.

It appears you are trying to create a generic object initializer. Reflection will work, but I would recommend investigating the System.Linq.Expressions namespace. You can use reflection to build a LambdaExpression that you can dynamically compile into a method that will then have much better performance than initializing your objects with reflection each time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜