Moh*_*vad 6 c# generics reflection properties typeof
A级
class A{
...
}
Run Code Online (Sandbox Code Playgroud)
B级
class B:A{
...
}
Run Code Online (Sandbox Code Playgroud)
C级
class C:A{
B[] bArray{get;set;}
}
Run Code Online (Sandbox Code Playgroud)
我想检查 T 是否具有 S 的属性类型,创建 S 的实例并分配给该属性:
public Initial<T,S>() where T,S : A{
if(T.has(typeof(S))){
S s=new S();
T.s=s;
}
}
Run Code Online (Sandbox Code Playgroud)
最好和最简单的方法是使用接口实现此功能。
public interface IHasSome
{
SomeType BArray {get;set;}
}
class C:A, IHasSome
{
public SomeType BArray {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以在你的泛型方法中转换对象:
public T Initial<T,S>() where T : new() where S : SomeType, new()
{
T t = new T();
if (t is IHasSome)
{
((IHasSome)t).BArray = new S();
}
return t;
}
Run Code Online (Sandbox Code Playgroud)
如果这不合适,您可以使用反射来检查属性并检查它们的类型。相应地设置变量。
小智 6
我同意@PatrickHofman的观点,这种方式更好,但是如果你想要更通用的东西来为类型的所有属性创建一个新实例,你可以使用反射来做到这一点:
public T InitializeProperties<T, TProperty>(T instance = null)
where T : class, new()
where TProperty : new()
{
if (instance == null)
instance = new T();
var propertyType = typeof(TProperty);
var propertyInfos = typeof(T).GetProperties().Where(p => p.PropertyType == propertyType);
foreach(var propInfo in propertyInfos)
propInfo.SetValue(instance, new TProperty());
return instance;
}
Run Code Online (Sandbox Code Playgroud)
然后:
// Creates a new instance of "C" where all its properties of the "B" type will be also instantiated
var cClass = InitializeProperties<C, B>();
// Creates also a new instance for all "cClass properties" of the "AnotherType" type
cClass = InitializeProperties<C, AnotherType>(cClass);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9275 次 |
| 最近记录: |