[英]How to Create an Instance of a Class in runtime derived from ObservableCollection<T>?
如何在派生自ObservableCollection的運行時中創建類的實例
視圖模型和模型如下:-C#編碼
public class Mobile
{
ObservableCollection<MobileModelInfo> SourceCollection = new ObservableCollection<MobileModelInfo>();
private void CreateObject(ObservableCollection<MobileModelInfo> Source)
{
/// Create an Object for MobileModelInfo Class in Runtime and add the Values
}
private ObservableCollection<MobileModelInfo> CostructMobileModel()
{
SourceCollection.Add(new MobileModelInfo { Name = "iPhone 4", Catagory = "Smart Phone", Year = "2011" });
SourceCollection.Add(new MobileModelInfo { Name = "S6", Catagory = "Ultra Smart Phone", Year = "2015" });
CreateObject(SourceCollection);
return SourceCollection;
}
}
public class MobileModelInfo
{
public string Name { get; set; }
public string Catagory { get; set; }
public string Year { get; set; }
}
從給出的示例中,您不需要ObservableCollection
類型的后備變量; 只要繼承自它,您的Mobile
類就成為MobileModelInfo
的可觀察集合。 注意:使用以下設計模式將其綁定起來要容易得多。
public class Mobile : ObservableCollection<MobileModelInfo>
{
public Mobile()
{
Add(new MobileModelInfo { Name = "foo", Category = "boo", Year = 1988 } );
}
public Mobile GetList()
{
return this;
}
}
我找到了這個問題的解決方案。 以下是C#函數,它在運行時從ObservableCollection派生一個類的實例
private void CreateObject(ObservableCollection<MobileModelInfo> Source)
{
var gType = Source.GetType();
string collectionFullName = gType.FullName;
Type[] genericTypes = gType.GetGenericArguments();
string className = genericTypes[0].Name;
string classFullName = genericTypes[0].FullName;
// Get the type contained in the name string
Type type = Type.GetType(classFullName, true);
// create an instance of that type
object instance = Activator.CreateInstance(type);
// List of Propery for the above created instance of a dynamic class
List<PropertyInfo> oProperty = instance.GetType().GetProperties().ToList();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.