Is it possible create a new instance of a generic type inside the body of a generic method?

Deadly 提交于 2019-12-12 00:57:38

问题


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#.


回答1:


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



回答2:


How can generic getDATA know what is TDal? It must be declared in the method getDATA or in the class containing the method i.e.

class MyGenericClass<TDal> where TDal:new()
{
    public List<TPer> getDATA<TPer>(TPer per, int acao) where TDal : new()
    {
        TDal dal = new TDal();
        List<TPer> lst = new List<TPer>();

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

In both cases the caller needs to know the TDal.

If you need to avoid this you can make something in getDATA that from per.GetType() retrieves the TDal type and then instantiate that class. I.e.

    public List<TPer> getDATA<TPer>(TPer per, int acao)
    {

        List<TPer> lst = new List<TPer>();

        IDal dal;

        switch (per.GetType().Name)
        {
            case "Person": 
                dal = new DalPerson();
                break;
            case "Car":
                dal = new DalCar();
                break;
            default:
                throw new InvalidOperationException("I dont like per");
        }

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


来源:https://stackoverflow.com/questions/24759951/is-it-possible-create-a-new-instance-of-a-generic-type-inside-the-body-of-a-gene

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!