代码之家  ›  专栏  ›  技术社区  ›  DirtyNative

泛型类型作为必须实现特定接口的参数

  •  0
  • DirtyNative  · 技术社区  · 7 年前

    我有一个方法,我想重新创建更通用的。

    public Task<bool> DoSomething<T>(T t) where T : Type, IAnyInterface
    

    类型

    但如果我调用这个方法,

    DoSomething(typeof(ObjectThatImplementsIAnyInterface));
    

    类型'系统类型'不能用作泛型类型或方法'DoSomething(…)'中的类型参数'T',没有从'系统类型'到'IAnyInterface'

    3 回复  |  直到 7 年前
        1
  •  4
  •   Mong Zhu Bart de Boer    7 年前

    不想传输实例,否则我想在DoSomething(…)方法中创建实例

    public Task<bool> DoSomething<T>() where T : IAnyInterface
    {
        Type type = typeof(T);
        // Or create the entire instance:
        T newInstance = Activator.CreateInstance<T>();
    }
    

    电话:

    DoSomething<ObjectThatImplementsIAnyInterface>();
    

    编辑:创建实例的另一种方法是要求无参数构造函数:

    public Task<bool> DoSomething<T>() where T : IAnyInterface, new()
    {
        T newInstance = new T();
    }
    

    documentation of CreateInstance

        2
  •  1
  •   Jamiec    7 年前

    你只是想

    public Task<bool> DoSomething<T>(T t) where T : IAnyInterface
    

    这就决定了 T 是必须实现的类型 IAnyInterface

    T型

    DoSomething(new ObjectThatImplementsIAnyInterface());
    

    有关类型约束的详细信息: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters


    我不想转移实例,否则我想在方法内部创建实例

    听起来你可能想要 new() 约束,允许您在方法内创建实例(注意:您需要一个无参数的ctor):

    public Task<bool> DoSomething<T>() where T : IAnyInterface, new()
    {
        // now you can do this:
        IAnyInterface inst = new T();
    }
    

    鉴于 DoSomething<ObjectThatImplementsIAnyInterface>()

    当然,你可以采取一种方法,在那里你可以传递它,或者创建它

    public Task<bool> DoSomething<T>(T t = null) where T : class, IAnyInterface, new()
    {
        // now you can do this:
        IAnyInterface inst = t ?? new T();
    }
    

    var runtimeType = typeof(T);
    
        3
  •  -1
  •   Pablo notPicasso    7 年前

    你说的不对。您需要传递实现接口的对象,而不是其类型:

    DoSomething(new ObjectThatImplementsIAnyInterface());