简体   繁体   中英

How to use a generic delegate in an interface

I'm trying to create an interface holding a generic delegate. I then want the classes implementing the interface to decide the actual type method, or preferably even return another delegate.

Below are some code describing what I'm trying to acheive.

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

Is this possible? Or is it impossible to switch delegates in such a manner?

I do not think that this is possible without making the interface generic. The common implementation would be:

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

Or, if you want to actually have a non-generic interface, use:

public interface ITest
{
    GenericMethod<object> someMethod;
}

You can also take a look at two interfaces IEnumerable and IEnumerable<T> to see how you can combine both generic and non-generic interfaces. Just implement the non-generic interface explicitly for use when you do not care about the concrete type.

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

You cannot do this because of inheritance principles. All, that works in ITest, should work in derived classes/interfaces. That means, if I'm able to use

GenericMethod<int> someMethod

(look at int) in ITest, I should be able to use it in TestA and TestB. You are trying to ignore this restriction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM