【问题标题】:Creating instance of a template type with class inheritance使用类继承创建模板类型的实例
【发布时间】:2013-02-10 13:16:29
【问题描述】:

我有一个似乎无法解决的问题。

假设我有这样的课程设置:

public abstract class GenericCustomerInformation
{
    //abstract methods declared here
}

public class Emails : GenericCustomerInformation
{
    //some new stuff, and also overriding methods from GenericCustomerInformation
}

public class PhoneNumber : GenericCustomerInformation
{
    //some new stuff, and also overriding methods from GenericCustomerInformation
}

现在假设我有这样的功能设置:

private void CallCustomerSubInformationDialog<T>(int iMode, T iCustomerInformationObject)
{
    //where T is either Emails or PhoneNumber

    GenericCustomerInformation genericInfoItem;

    //This is what I want to do:
    genericInfoItem = new Type(T);

    //Or, another way to look at it:
    genericInfoItem = Activator.CreateInstance<T>(); //Again, does not compile
}

CallCustomerSubInformationDialog&lt;T&gt; 函数中,我有一个基本类型为GenericCustomerInformation 的变量,我想用T 中的任何内容对其进行实例化(派生类型之一:EmailsPhoneNumber )

使用一堆if 条件很简单,但我不想做任何有条件的事情,因为这会使我的代码比它需要的大得多..

【问题讨论】:

    标签: c# templates inheritance activator


    【解决方案1】:

    可能是这样的吗? (还是我误解了?)

    private void CallCustomerSubInformationDialog<T>(int iMode, T iCustomerInformationObject) where T: GenericCustomerInformation, new()
    {
        //where T is either Emails or PhoneNumber
        GenericCustomerInformation genericInfoItem;
        //This is what you could try to do:
        genericInfoItem = new T();
    
    }
    

    注意:注意对 T... 的限制。

    【讨论】:

    • 谢谢!不知道我是怎么错过的:p
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多