How to use an alias type as a generic type parameter in C# [duplicate]

给你一囗甜甜゛ 提交于 2019-12-13 02:59:17

问题


How do you pass an alias type defined by using to the generic class?

I tried the following code:

using ID = Int32; // it might be replaced with `String`.
using CC = C<ID>;

public class C<T> {
    T id;
}

and there will be an error:

Error CS0246 The type or namespace name 'ID' could not be found (are you missing a using directive or an assembly reference?)

But the using directive is right above the line where the error occurs. Did I miss something?


回答1:


I do not really know what you are trying to achieve with this, but you can, however, do something similar with inheritance

public class CC : C<ID>
{
}

The class CC will derive from C<T> with a concrete type. Hence CC.T will be of type Int32 (or whatever).




回答2:


Don't use an alias.

public class C<T> {
   T id;
}

...

void Foo() {
  var x = new C<Int32>();

  var y = new C<string>();
}


来源:https://stackoverflow.com/questions/45366303/how-to-use-an-alias-type-as-a-generic-type-parameter-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!