簡體   English   中英

如何在接口中使用泛型委托

[英]How to use a generic delegate in an interface

我正在嘗試創建一個包含通用委托的接口。 然后,我希望實現該接口的類決定實際的類型方法,或者最好甚至返回另一個委托。

以下是一些代碼,描述了我要達到的目標。

public delegate void GenericMethod<T>(T arg);
public delegate void StringMethod(string str);
public delegate void ByteMethod(byte bt);

public interface ITest
{
    GenericMethod<T> someMethod;    
}

public class TestA : ITest
{
    public GenericMethod<string> someMethod
    {
         get 
         {
               return stringMethod; //which is of type StringMethod(string str), defined above
         }
    }
}

public class TestB : ITest
{
    public GenericMethod<byte> someMethod
    {
         get 
         {
               return byteMethod; //which is of type ByteMethod(byte bt);, defined above
         }
    }
}

這可能嗎? 還是不可能以這種方式切換代表?

我認為如果不使接口通用,就不可能做到這一點。 常見的實現方式是:

public interface ITest<T>
{
    GenericMethod<T> someMethod;
}

或者,如果您想真正擁有一個非通用接口,請使用:

public interface ITest
{
    GenericMethod<object> someMethod;
}

您還可以查看IEnumerableIEnumerable<T>兩個接口,以了解如何組合通用接口和非通用接口。 只要不關心具體類型,就可以顯式實現非泛型接口以供使用。

public delegate void GenericMethod<T>(T arg);
public delegate void StringMethod(string str);
public delegate void ByteMethod(byte bt);

public interface ITest<T>
{
    GenericMethod<T> someMethod { get; };
}

public class TestA : ITest<string>
{
    public GenericMethod<string> someMethod
    {
        get
        {
            return stringMethod; //which is of type StringMethod(string str), defined above
        }
    }
}

public class TestB : ITest<byte>
{
    public GenericMethod<byte> someMethod
    {
        get
        {
            return byteMethod; //which is of type ByteMethod(byte bt);, defined above
        }
    }
}

由於繼承原則,您無法執行此操作。 所有可以在ITest中工作的方法都應該在派生類/接口中工作。 也就是說,如果我能夠使用

GenericMethod<int> someMethod

(看int)在ITest中,我應該能夠在TestA和TestB中使用它。 您正在嘗試忽略此限制

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM