繁体   English   中英

如何在接口中创建可选的泛型方法?

[英]How to create an optional generic method in an interface?

我的问题太简单了,我有一个Interface包含一种method

界面:

public interface IAbstract
{
    void DoSomething();
}

我有两个类会在接口中包含相同的方法,所以我想让它们(类)实现接口。

问题:唯一的问题是在其中一个类中此方法将正常实现,但在另一个 class 中,此方法将作为通用方法实现

我的想法是代码:

第一个 class:

public class ClassOne:IAbstract
{
    public void DoSomething()
    {
        throw new System.NotImplementedException();
    }
} 

第二个 class:

public class ClassTwo:IAbstract
{
    public void DoSomething<int>()
    {
        throw new System.NotImplementedException();
    }
}

我知道这给了我一个错误,但我的问题是有什么方法可以在不创建单独接口的情况下做我认为的事情?

你应该这样做:

public interface IAbstractRoot<T>
{
    void DoSomthing<TT>() where TT : T;
}

public abstract class IAbstractRoot : IAbstractRoot<object>
{
    public void DoSomthing<TT>()
    {
        DoSomthing();
    }

    public abstract void DoSomthing();
}

孩子应该是这样的:

public class Child1 : IAbstractRoot<int>
{
    void IAbstractRoot<int>.DoSomthing<TT>()
    {
        throw new System.NotImplementedException();
    }
}

public class Child2 : IAbstractRoot
{
    public override void DoSomthing()
    {

    }
}

您可以使用Variant Generic Interfaces完成此操作。

void Main()
{
    var a = new a();
    var b = new b<string>();
    
    a.DoSomething(1);
    b.DoSomething("Here is a string");
}

public interface IAbstract<in T>
{
    void DoSomething(T param1);
}

public class a : IAbstract<int>
{
    public void DoSomething(int param1)
    {
        Console.WriteLine($"I am specificly an int {param1}");
    }
}

public class b<T> : IAbstract<T>
{
    public void DoSomething(T param1)
    {
        Console.WriteLine($"I am a generic something {param1}");
    }
}

你有几个设计选项来获得你想要的。

    static void Main(string[] args)
    {
        var one = new ClassOne();
        one.DoSomething(); 
        var two = new ClassTwo();
        two.DoSomething();
        two.DoSomething<int>();
        var three = new ClassThree<int>();
        three.DoSomething();
        three.DoSomething(100);
    }

和代码

public interface IAbstract
{
    void DoSomething();
}
public interface IAbstract<in T> : IAbstract
{
    void DoSomething(T arg);
}

public class ClassOne : IAbstract
{
    public void DoSomething()
    {
        Debug.WriteLine("DoSomething()");
    }
}
public class ClassTwo : IAbstract
{
    public void DoSomething()
    {
        Debug.WriteLine("DoSomething()");
    }
    public void DoSomething<T>()
    {
        Debug.WriteLine("DoSomething<T>()");
    }
}
public class ClassThree<T> : IAbstract where T : new()         
{
    public void DoSomething()
    {
        Debug.WriteLine("DoSomething()");
    }
    public void DoSomething(T arg)
    {
        Debug.WriteLine("DoSomething(T arg)");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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