类 A
class A{
...
}
B类
class B:A{
...
}
类 C
class C:A{
B[] bArray{get;set;}
}
我希望检查T是否具有S的属性类型,创建S的实例并将其赋值给该属性:
public Initial<T,S>() where T,S : A{
if(T.has(typeof(S))){
S s=new S();
T.s=s;
}
}
类 A
class A{
...
}
B类
class B:A{
...
}
类 C
class C:A{
B[] bArray{get;set;}
}
public Initial<T,S>() where T,S : A{
if(T.has(typeof(S))){
S s=new S();
T.s=s;
}
}
public interface IHasSome
{
SomeType BArray {get;set;}
}
class C:A, IHasSome
{
public SomeType BArray {get;set;}
}
然后你可以在通用方法中对对象进行转换:
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;
}
void
。 - Patrick Hofman我同意@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;
}
然后:
// 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);