简体   繁体   English

使用泛型在抽象类中调用构造函数

[英]Call constructor in abstract class with generics

I have the following base class which is abstract: 我有以下抽象的基类:

public abstract class MasterDataViewModel<TPrimaryModel> : ViewModel
    where TPrimaryModel : TwoNames, new()
{
    ...
}

I have some derived classes like: 我有一些派生类,如:

public class ConsignorViewModel : MasterDataViewModel<Consignor>
{
    protected override void Find()
    {           
        ...
        foreach (Consignor consignor in consignors)
        {
            ConsignorViewModel viewModel = new ConsignorViewModel(consignor, consignor.Address);
            SearchResults.Add(viewModel);
        }
        ...

    }
}

I would like to move the Find method to my base class. 我想将Find方法移至我的基类。 The problem is the constructor call which is not possible in my abstract class. 问题是构造函数调用,这在我的抽象类中是不可能的。 It has to be something like this: 它必须是这样的:

protected override void Find()
{         
    ...
    foreach (TPrimaryModel primaryModel in results)
    {
        MasterDataViewModel<TPrimaryModel> viewModel = new MasterDataViewModel(primaryModel, primaryModel.Address);
        SearchResults.Add(viewModel);
    }
    ...
}

It's not working as constructor calls in abstract classes are not allowed. 它不起作用,因为不允许在抽象类中进行构造函数调用。 Any other solution? 还有其他解决方案吗? I thought about another generic. 我想到了另一个通用名称。 Problem is that a new constraint cannot have any parameters so this doesn't work, too. 问题是新约束不能有任何参数,因此也不起作用。

This design of classes doesn't sound to be right if the Find() method inside the MasterDataViewModel / ConsignorViewModel class is creating the instance of the class. 类的这种设计不健全是正确的,如果Find()里面方法MasterDataViewModel / ConsignorViewModel类是创建类的实例。 This seems like the Find() method should be a static helper class, but we don't see all the code of the Find() method so I cannot say it for sure. 似乎Find()方法应该是一个静态帮助器类,但是我们看不到Find()方法的所有代码,因此我不能肯定地说。 If not a static method, then the Find() functionality should be moved out to another helper class. 如果不是静态方法,则应将Find()功能移到另一个帮助程序类。

Either create an abstract method in the base class "CreateViewModel" that you override in each model. 在每个模型中都覆盖的基类“ CreateViewModel”中创建一个抽象方法。 Or use the Activator.CreateInstance method to create an instance of the this.GetType() subclass. 或使用Activator.CreateInstance方法创建this.GetType()子类的实例。

The first one is the cleanest. 第一个是最干净的。 That way your class serves as a factory for itself. 这样,您的班级将为自己服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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