[英]Check T generic type has property S (generic) in c#
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;
}
}
最好和最簡單的方法是使用接口來實現此功能。
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;
}
如果不合適,則可以使用反射遍歷屬性並檢查其類型。 相應地設置變量。
我同意@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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.