【问题标题】:How to use a generic delegate in an interface如何在接口中使用泛型委托
【发布时间】:2011-09-30 13:21:07
【问题描述】:

我正在尝试创建一个包含通用委托的接口。然后我希望实现接口的类决定实际的类型方法,或者最好甚至返回另一个委托。

下面是一些代码,描述了我想要实现的目标。

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

这可能吗?或者以这种方式切换代表是不可能的?

【问题讨论】:

    标签: c# generics interface delegates


    【解决方案1】:

    如果不使接口通用,我认为这是不可能的。常见的实现是:

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

    或者,如果您想真正拥有一个非泛型接口,请使用:

    public interface ITest
    {
        GenericMethod<object> someMethod;
    }
    

    您还可以查看IEnumerableIEnumerable&lt;T&gt; 两个接口,了解如何结合通用接口和非通用接口。当您不关心具体类型时,只需显式实现非泛型接口即可使用。

    【讨论】:

      【解决方案2】:

      由于继承原则,您不能这样做。所有在 ITest 中工作的东西都应该在派生类/接口中工作。这意味着,如果我能够使用

      GenericMethod<int> someMethod
      

      (看看 int)在 ITest 中,我应该可以在 TestA 和 TestB 中使用它。您试图忽略此限制

      【讨论】:

        【解决方案3】:
        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
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-02-07
          • 1970-01-01
          • 1970-01-01
          • 2012-12-05
          • 1970-01-01
          • 2023-01-26
          • 1970-01-01
          相关资源
          最近更新 更多