相关疑难解决方法(0)

通用约束,其中T:struct和T:class

我想区分以下情况:

  1. 普通值类型(例如int)
  2. 可以为null的值类型(例如int?)
  3. 引用类型(例如string) - 可选地,我不关心这是否映射到上面的(1)或(2)

我已经提出了以下代码,它适用于案例(1)和(2):

static void Foo<T>(T a) where T : struct { } // 1

static void Foo<T>(T? a) where T : struct { } // 2
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试像这样检测case(3),它就不会编译:

static void Foo<T>(T a) where T : class { } // 3
Run Code Online (Sandbox Code Playgroud)

错误消息是类型'X'已经定义了一个名为'Foo'的成员,它具有相同的参数类型.好吧,不知何故,我无法在where T : struct和之间产生影响where T : class.

如果我删除第三个函数(3),以下代码也不会编译:

int x = 1;
int? y = 2;
string z = "a";

Foo (x); // OK, …
Run Code Online (Sandbox Code Playgroud)

c# generics struct constraints class

50
推荐指数
4
解决办法
5万
查看次数

C#通用接口专业化

我想知道在C#中以某种方式专门化通用接口方法是否有可能?我发现了类似的问题,但没有完全像这样.现在我怀疑答案是"不,你不能",但我想确认一下.

我所拥有的是以下内容.

public interface IStorage
{
    void Store<T>(T data);
}

public class Storage : IStorage
{
    public void Store<T>(T data)
    {
        Console.WriteLine("Generic");
    }

    public void Store(int data)
    {
        Console.WriteLine("Specific");
    }
}

class Program
{
    static void Main(string[] args)
    {
        IStorage i = new Storage();
        i.Store("somestring"); // Prints Generic
        i.Store(1); // Prints Generic
        Storage s = (Storage)i;
        s.Store("somestring"); // Prints Generic
        s.Store(1); // Prints Specific
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法让它在通过界面调用时使用专门版的Store?如果没有,有没有人知道C#以这种方式处理通用参数的确切原因?

编辑:如果C#无法在多个步骤中解析模板参数,则可以解决该问题.

void Foo<T>(T t)
{
    SubFoo(t);
}

void SubFoo<T>(T t)
{
    Console.WriteLine("Generic");
} …
Run Code Online (Sandbox Code Playgroud)

c#

15
推荐指数
1
解决办法
2万
查看次数

标签 统计

c# ×2

class ×1

constraints ×1

generics ×1

struct ×1