[英]C# nameof generic type without specifying type
Assume I have the type 假设我有类型
public class A<T> { }
and somewhere in the code I want to throw an exception related to incorrect usage of that type: 在代码中的某处我想抛出与该类型的错误使用相关的异常:
throw new InvalidOperationException("Cannot use A<T> like that.");
So far, so good, but I don't want to hardcode the classes name, so I thought I could maybe use 到目前为止,这么好,但我不想硬编码类名,所以我想我也许可以使用
throw new InvalidOperationException($"Cannot use {nameof(A<T>)} like that.");
instead, but in this context I don't know the exact type T
. 相反,但在这种情况下,我不知道确切的类型
T
So I thought maybe I could do it with template specialization like in C++: 所以我想也许我可以用C ++中的模板特化来做到这一点:
throw new InvalidOperationException($"Cannot use {nameof(A)} like that.");
or 要么
throw new InvalidOperationException($"Cannot use {nameof(A<>)} like that.");
but those yield 但那些产量
Incorrect number of type parameters.
类型参数数量不正确。
and 和
Type argument is missing.
缺少类型参数。
I absolutely don't want to hardcode the classes name for it might change later. 我绝对不想硬编码类名,因为它可能会在以后更改。 How can I get the name of the class, preferably via
nameof
? 我怎样才能得到班级的名字,最好是通过
nameof
?
Optimally, what I want to achieve is "Cannot use A<T> like that."
最理想的是,我想要实现的是
"Cannot use A<T> like that."
or "Cannot use A like that."
或者
"Cannot use A like that."
. 。
If you don't care about displaying T
, you can just use eg nameof(A<object>)
, assuming object
complies with the generic type constraints. 如果您不关心显示
T
,您可以使用例如nameof(A<object>)
,假设object
符合泛型类型约束。
This results in "Cannot use A like that." 这导致“不能使用A那样的”。
If you want to print exactly A<T>
, you could use: 如果要打印
A<T>
,可以使用:
$"{nameof(A<T>)}<{nameof(T)}>"
But only from within the class, as T
does not exist elsewhere. 但只有在课堂内,因为
T
在其他地方不存在。
Depending on the place you want to raise that exception, you can use the type. 根据您要引发该异常的位置,您可以使用该类型。
On the instance, call this.GetType()
and then get the Name
or FullName
property: 在实例上,调用
this.GetType()
然后获取Name
或FullName
属性:
throw new InvalidOperationException($"Cannot use {this.GetType().Name} like that.");
Have you tried: 你有没有尝试过:
typeof(T).FullName;
or 要么
t.GetType().FullName;
Hope it works for you. 希望对你有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.