是否有可能在泛型方法体内创建泛型类型的新实例? [英] Is it possible create a new instance of a generic type inside the body of a generic method?

查看:138
本文介绍了是否有可能在泛型方法体内创建泛型类型的新实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设下面的方法,我知道它不起作用:

我想创建一个新的泛型类型的实例

  public List< TPer> getDATA< TPer>(TPer per,int acao)其中TDal:new()
{
//是否可以在泛型方法体内创建泛型类型的新实例?
TDal dal = new TDal(); //< - 我知道它不正确
List< TPer> lst = new List< TPer>();

lst = dal.getDATA(per,acao);
返回lst;
}

我可以这样写:

 列表< TPer> getDATA< TPer,TDal>(TPer per,int acao)其中TDal:new()

将调用此方法的程序不能访问 TDal



是否可以使用空参数?或者在泛型方法体内创建一个泛型类型的新实例?



< TDal> 会也是通用的,但我不知道是否有可能在C#中使用此泛型方法内部创建它作为新的泛型类型。

解决方案

你可以让你的泛型实现一个接口。然后在您的泛型方法中放置限制,只接受实现该接口的类型。这将允许你调用你新构建的项目的方法,因为它已知有这些方法。

  public interface ITest 
{
void DoSomething();
}

public void GetData< T,U>(T varA,int acao)其中U:ITest,new()
{
var item = new U ();
item.DoSomething();
}


Assuming the following method, and I know it does not work:

I want to create a new instance of a generic type

public List<TPer> getDATA<TPer>(TPer per, int acao) where TDal: new()
{
    //Is it possible create a new instance of a generic type inside the body of a generic method?
    TDal dal = new TDal(); //<-- I know it is NOT OK 
    List<TPer> lst = new List<TPer>();

    lst = dal.getDATA(per, acao);
    return lst;
}

I could write something like this:

List<TPer> getDATA<TPer,TDal>(TPer per, int acao) where TDal: new()

But, the program that will call this method dont have access to TDal:

Is it possible to call this method using an empty parameter? or create a new instance of a generic type inside the body of a generic method?

<TDal> would be generic too, but I don't know if it's possible create it, as a new generic type, inside of this generic method in C#.

解决方案

You can have your generic type implement an interface. Then place restrictions in your generic method to only accept types that implement that interface. This will allow you to call methods on your newly constructed item as it's known to have those methods.

public interface ITest
{
    void DoSomething();
}

public void GetData<T, U>(T varA, int acao) where U: ITest, new()
{
    var item = new U();
    item.DoSomething();
} 

这篇关于是否有可能在泛型方法体内创建泛型类型的新实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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