对泛型模板类的c#反思
下面是我的代码示例:对泛型模板类的c#反思,c#,generics,reflection,C#,Generics,Reflection,下面是我的代码示例: 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 | Bi
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;**
}
公共抽象类
{
公共列表GetSomething(字符串q)
{
**列表=新列表()**
类型=类型(T);
PropertyInfo[]props=type.GetProperties(BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance);
foreach(道具中的属性信息)
{
//此时,我需要从数据源查询返回信息
//并根据返回的结果构建成员(设置值)
//需要将其添加到包含每个属性的T的列表中
//内设置为值。“某些值”应为所需的对象实例
//按属性信息的类型。
info.SetValue(类型“Some Value”,null);
**列表。添加(类型)**
}
}
**退货清单**
}
信息。由于模板类型的原因,无法访问SetValue(对象,对象,对象[]),对吗?我在这里的问题是,如何设置T中包含的属性的值
编辑:这个问题连我自己都弄糊涂了。我已经修改了上述程序,以代表我的直接需要
谢谢,
埃里克我看不出这有什么意义。您试图在T的实例上设置属性(如bindingflags所示),但您正在将
typeof(T)
-a Type-作为第一个参数传递给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);
}
}
}
公共抽象类Foo
{
公共列表GetSomethingFrom(T实例)
{
类型=类型(T);
PropertyInfo[]props=type.GetProperties(BindingFlags.Public|
BindingFlags.IgnoreCase | BindingFlags.Instance);
foreach(道具中的属性信息)
{
info.SetValue(实例“Some Value”,null);
}
}
}
在本例中,我们将T的一个实例传递给GetSomethingFrom方法,然后将实例传递给SetValue。跟着
-在中,最好断言您正在设置的属性实际上也是字符串,或者您对SetValue的调用(例如,“Some Value”,null)将抛出
似乎您正在尝试创建通用对象初始值设定项。反射将起作用,但我建议调查System.Linq.Expressions名称空间。您可以使用反射构建一个LambdaExpression,动态编译成一个方法,该方法的性能比每次使用反射初始化对象要好得多。您的目标是什么?与“info”对应的属性是静态的吗?您试图设置属性值的对象是什么?您的问题太让人困惑了。这个方法到底应该做什么?现在,它返回了一个列表,名为GetSomething,但您没有返回任何内容,实际上,您正在尝试设置一些内容,而不是获取它。