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

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

问题描述

您可以看到我想要的(但没有)做如下code:

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

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

任何帮助将是很大的AP preciated。

Any help would be greatly appreciated.

编辑:

上下文如下。我在玩弄一个自定义的控制器类为所有控制器从派生,用标准化的方法。因此,在上下文中,我需要创建所述控制器类型的对象的新实例。因此,在写作的时候,它是这样的:

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);
    }

所以我决定反映了最简单的在这里。我同意,当然考虑到问题的初步声明,最合适的答案标记为正确的是一个使用新的()的约束。我有固定的了。

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 可能是因为没有一个默认的构造函数的类:在这种情况下新T()会是一个无效的声明。该新()约束说, T 必须有一个默认的构造函数,这使得新款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天全站免登陆