2017-04-11 115 views
0

常用的方法我已经类的名称和AA类有许多其他用户定义的对象的属性(BC等)。对于使用A类,我需要为创建(任何)对象初始化

new A{ B = new B(), C = new C() ...} 

这种情况发生很多次在我的项目创建实例,它使我的代码有点凌乱的。

现在我需要一些代码(或现有的库,框架)来使用较少的代码创建这种类的实例。

+0

根本不清楚你在问什么,或者你期待什么作为答案。对于任何您遇到的具体问题,请包括[mcve] **。另请阅读[我如何提出一个好问题](http://stackoverflow.com/help/how-to-ask)。 – Igor

+0

使用你的类的构造函数 – Pikoh

+0

'less code'是什么意思?这个问题太泛泛。你能提供** [mcve] **吗? – Smartis

回答

1

好吧,让我们用Reflection,我创建了一个BaseClass,它看起来像,

public class Base { 

      public Base() { 
       Type type = this.GetType(); // gets current type 
       var props = type.GetProperties(); // get current type's properties 

       foreach (var item in props) // B and C 
       { 
        object instance = Activator.CreateInstance(item.PropertyType); // create instace of both B and C 
        item.SetValue(this, instance); // set B property to new value which we have created instance 

       } 


      } 
     } 

而且这是一个应该BaseClass导出并应使用基本的构造函数,这样我们的容器类,

public class A : Base 
     { 
      public A() : base() { 

      } 
      public B _B { get; set; } 
      public C _C {get;set;} 
     } 

Implemeted一个在此之后,刚刚从A创建instace并检查性能,

希望帮助,

+0

我需要通用的方法来创建任何类实例。在我的问题中,类A只是样本类。 – Murad

+0

请参阅编辑@Murad – Berkay

+0

这是一个很好的方法,但是当我不需要每次创建新对象时都要调用对象初始化器。 – Murad

0

那是什么(构造函数,方法)重载是有:)见下面的例子:

public class ClassA { 

    public ClassA() { 
     // Do some generic initialization here 
     this.ClassB = new ClassB(); 
     this.ClassC = new ClassC(); 
    } 

    // Always call the base constructor using : this() 
    public ClassA(string name, int age) : this() { 
     this.Name = name; 
     this.Age = age; 
    } 

    // chain to another, 'simpler' constructor by doing : this(name, age) 
    public ClassA(string name, int age, ClassB classB) : this(name, age) { 
     this.ClassB = classB; 
    } 

    public ClassA(string name, int age, ClassB classV, ClassC classC) : this(name, age, classV) { 
     this.ClassC = classC; 
    } 
    public string Name { get; set; } 
    public int Age { get; set; } 
    public ClassB ClassB { get; set; } 
    public ClassC ClassC { get; set; } 
} 

public class ClassB { 
    public string School { get; set; } 
    public string Class { get; set; } 
} 

public class ClassC { 
    public string Area { get; set; } 
    public string Suburb { get; set; } 
} 

,然后调用它像这样:

public SomeMethod() { 
    ClassA = new ClassA("John", 40, new ClassB(), new ClassC()); 
} 

你可以真正通过重载构造函数使类型初始化变得容易很多

+0

我需要通用的方法来创建任何类实例。在我的问题中,类A只是样本类。 – Murad