将C#泛型用作构造函数名称的语法是什么? [英] What is the syntax to use C# generics as a constructor name?

查看:71
本文介绍了将C#泛型用作构造函数名称的语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多继承自Item<T>的类.

每个类都有一个Create()方法,我想将其移至Item<T>.

Each class has a Create() method that I would like to move up into Item<T>.

但是以下代码收到错误"由于没有new()约束而无法创建变量类型'T'的实例"

Yet the following code gets the error "Cannot create an instance of the variable type 'T' because it does not have the new() constraint":

T item = new T(loadCode);

要执行此操作的更正语法是什么?

What is the correction syntax to do this?

public abstract class Item<T> : ItemBase
{

    public static T Create(string loadCode)
    {
        T item = new T(loadCode);

        if (!item.IsEmpty())
        {
            return item;
        }
        else
        {
            throw new CannotInstantiateException();
        }
    }

推荐答案

这是不可能的.您只能使用new()约束来强制存在构造函数.

It's not possible. You can only use new() constraint to force existence of a constructor.

一种解决方法是采用Func<InputType, T>(在您的示例中为Func<string,T>)委托作为输入参数,它将为我们创建对象.

A workaround is to take a Func<InputType, T> (Func<string,T> in your example) delegate as input parameter that'll create the object for us.

public static T Create(string loadCode, Func<string,T> construct)
{
    T item = construct(loadCode);

    if (!item.IsEmpty())
    {
        return item;
    }
    else
    {
        throw new CannotInstantiateException();
    }
}

并调用:Item<T>.Create("test", s => new T(s));

这篇关于将C#泛型用作构造函数名称的语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆