接口,泛型,c#

Nic*_*k B 0 c# generics interface

我对c#的了解很少.

做以下事情的正确方法是什么?

目标是创建一个getvalue()可以跨多种结构工作的接口.

public interface IBOB 
{ 
    T GetValue<T>() where T:struct
}

class YAY:IBOB
{
    public bool GetValue<bool>()
    {
      return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

我怀疑你的意思是:

public interface IBOB<T> where T:struct
{ 
    T GetValue(); 
}
Run Code Online (Sandbox Code Playgroud)

那么YAY:IBOB<bool>它支持的其他类型:

class YAY : IBOB<bool>
{
    public bool GetValue()
    {
        return true;
    }    
}
Run Code Online (Sandbox Code Playgroud)

请注意,由于命名/解析,您可能需要对多种类型使用显式接口实现:

class YAY : IBOB<bool>, IBOB<int>
{
    bool IBOB<bool>.GetValue() => true;
    int IBOB<int>.GetValue() => 42;
}
Run Code Online (Sandbox Code Playgroud)

如果YAY:IBOB(您的原始),那么您将需要该方法是通用的:

public bool GetValue<T>() {...}
Run Code Online (Sandbox Code Playgroud)

否则它与签名不符.