C# 创建新的 T() [英] C# Create New T()

查看:43
本文介绍了C# 创建新的 T()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以看到我正在尝试(但失败)使用以下代码做什么:

You can see what I'm trying (but failing) to do with the following code:

protected T GetObject()
{
    return new T();
}

任何帮助将不胜感激.

上下文如下.我正在玩一个自定义控制器类,用于所有控制器的派生,并使用标准化方法.因此,在上下文中,我需要创建控制器类型对象的新实例.所以在撰写本文时,它是这样的:

The context was as follows. I was playing around with a custom controller class for all controllers to derive from, with standardised methods. So in context, I needed to create a new instance of the object of the controller type. So at time of writing, it was something like:

public class GenericController<T> : Controller
{
    ...

    protected T GetObject()
    {
        return (T)Activator.CreateInstance(ObjectType);
    }        

    public ActionResult Create()
    {
        var obj = GetObject()

        return View(obj);
    }

所以我决定在这里反射是最简单的.我同意,当然考虑到问题的初始陈述,标记为正确的最合适的答案是使用 new() 约束的答案.我已经解决了.

And so I decided reflection was easiest here. I agree that, certainly given the initial statement of the question, the most appropriate answer to mark as correct was the one using the new() constraint. I have fixed that up.

推荐答案

看看 新约束

public class MyClass<T> where T : new()
{
    protected T GetObject()
    {
        return new T();
    }
}

T 可能是一个没有默认构造函数的类:在这种情况下 new T() 将是一个无效的语句.new() 约束表示 T 必须有一个默认构造函数,这使得 new T() 合法.

T could be a class that does not have a default constructor: in this case new T() would be an invalid statement. The new() constraint says that T must have a default constructor, which makes new T() legal.

您可以将相同的约束应用于泛型方法:

You can apply the same constraint to a generic method:

public static T GetObject<T>() where T : new()
{
    return new T();
}

如果需要传递参数:

protected T GetObject(params object[] args)
{
    return (T)Activator.CreateInstance(typeof(T), args);
}

这篇关于C# 创建新的 T()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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