问题
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