【问题标题】:How to Create an Instance of a Class in runtime derived from ObservableCollection<T>?如何在从 ObservableCollection<T> 派生的运行时创建类的实例?
【发布时间】:2016-02-17 16:07:15
【问题描述】:

如何在运行时创建派生自 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; }
}

【问题讨论】:

  • 你所做的一切都是错误的。停止。拿一本书。阅读它。

标签: c# oop object instance observablecollection


【解决方案1】:

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

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

    public Mobile GetList()
    {
        return this;
    }
}

【讨论】:

    【解决方案2】:

    我得到了这个问题的解决方案。以下是它在运行时创建从 ObservableCollection 派生的类的实例的 C# 函数

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-29
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 2013-07-05
      • 2013-11-16
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      相关资源
      最近更新 更多