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



我的问题太简单了,我有一个包含一个methodInterface

接口:

public interface IAbstract
{
void DoSomething();
}

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

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

我的想法作为代码:

头等舱:

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

二等:

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()
{
}
}

只需为接口分配一个泛型参数,然后在实现时在那里提供一个具体的类型。为了保持它的通用性,只需为类b提供一个通用性,这样你就可以将它传递给接口,比如so..

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)");
}
}

最新更新