【问题标题】:How can I instantiate a property of a class by knowing just the type如何通过只知道类型来实例化类的属性
【发布时间】:2018-08-21 10:25:11
【问题描述】:

我有一个包含其他几个类作为属性的类。最初,没有实例化任何属性。我想通过在 Load 函数中传递属性本身来实例化单个属性。

public class MyMainClass
{
    public ClassA A { get; set; }
    public ClassB B { get; set; }
    public ClassC C { get; set; }
    // ...
    // ...
    // Many more. All these classes are inherited from Class0

    public void Load(Class0 UnknownClass)
    {
        if ((UnknownClass) is ClassA) A = new ClassA();    
        if ((UnknownClass) is ClassB) B = new ClassB();    
        if ((UnknownClass) is ClassC) C = new ClassC();
        //  and so on... This should to be done in a loop 
    }
}

public void Main()
{
    MyMainClass MyObj = new MyMainClass();
    MyObj.Load(MyObj.ClassA);  // This should instantiate MyObj.ClassA
    MyObj.ClassA.SomeMethod();
}

Class0ClassAClassB 等的基类。

这很好用。 但我不想为每个类写一大堆比较。我需要遍历属性,找到匹配的类型并实例化它。我可能需要使用 system.reflection,但不确定如何...

还有其他类似的答案,但每个都根据传递的类型实例化一个新对象。我需要实例化类的属性。

【问题讨论】:

标签: .net object system.reflection


【解决方案1】:

好的,结合其他几个答案,我终于想通了:

public void Load<T>() where T : new()
{
    object lObj = Activator.CreateInstance(typeof(T));  // instantiate a new object of type passed

    // Loop through properties and assign object to the property that matches its type
    System.Reflection.PropertyInfo[] lProps = typeof(MyMainClass).GetProperties();
    foreach (System.Reflection.PropertyInfo lProp in lProps)
    {
        if ((typeof(T).ToString() == lProp.PropertyType.Name)) lProp.SetValue(this, lObj);
    }
}

【讨论】:

    猜你喜欢
    • 2018-05-15
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    相关资源
    最近更新 更多