如何在运行时从ObservableCollection <t>派生类创建实例?

时间:2015-11-16 14:10:51

标签: c# oop object instance observablecollection

如何在运行时从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; }
}

2 个答案:

答案 0 :(得分:0)

从您给出的示例中,您不需要ObservableCollection类型的支持变量;只是从它继承而你的Mobile类成为MobileModelInfo s的可观察集合。注意:使用以下设计模式绑定它会容易得多。

public class Mobile : ObservableCollection<MobileModelInfo>
{
    public Mobile()
    {
        Add(new MobileModelInfo { Name = "foo", Category = "boo", Year = 1988 } );
    }

    public Mobile GetList()
    {
        return this;
    }
}

答案 1 :(得分:0)

我找到了解决这个问题的方法。以下是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();
}