简体   繁体   English

如何在派生自ObservableCollection的运行时中创建类的实例 <T> ?

[英]How to Create an Instance of a Class in runtime derived from ObservableCollection<T>?

How to Create an Instance of a Class in runtime derived from ObservableCollection 如何在派生自ObservableCollection的运行时中创建类的实例

The View Model and Model is given below :- C# Coding 视图模型和模型如下:-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; }
}

From the example you've given you don't need a backing variable of ObservableCollection type; 从给出的示例中,您不需要ObservableCollection类型的后备变量; just inherit from it and your Mobile class becomes an observable collection of MobileModelInfo s. 只要继承自它,您的Mobile类就成为MobileModelInfo的可观察集合。 Note: it's much easier to bind to it using the below design pattern. 注意:使用以下设计模式将其绑定起来要容易得多。

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

    public Mobile GetList()
    {
        return this;
    }
}

I Got the Solution for this issue. 我找到了这个问题的解决方案。 The Following is the C# Function it Create an Instance of a Class in runtime derived from ObservableCollection 以下是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM