我已经对类,方法,字段,属性和枚举进行了测试,以查看是否存在不正确的情况?
using System;
public class Program
{
public static void Main()
{
var fooType = typeof(Foo);
ThrowIfNotEqual(fooType.Name, nameof(Foo));
var fi = fooType.GetField(nameof(Foo.field));
ThrowIfNotEqual(fi.Name, nameof(Foo.field));
var pi = fooType.GetProperty(nameof(Foo.property));
ThrowIfNotEqual(pi.Name, nameof(Foo.property));
var mi = fooType.GetMethod(nameof(Foo.method));
ThrowIfNotEqual(mi.Name, nameof(Foo.method));
var fi2 = fooType.GetNestedTypes()[0];
ThrowIfNotEqual(fi2.Name, nameof(Foo.myEnum));
ThrowIfNotEqual("TestThisMethod", "WorksAsExpected");
}
public static void ThrowIfNotEqual(string a, string b)
{
if (a != b) throw new InvalidOperationException($"Are Not Equal: {a} != {b}");
}
public class Foo
{
public string field;
public string property { get; set; }
public void method() { }
public enum myEnum
{
A
}
}
}
结果:
运行时异常(第-1行):不等于:TestThisMethod!= WorksAsExpected
答案 0 :(得分:9)
是否总是
nameof()
等于typeof().Name
?
作为一个例子,没有很多方法可以解决这个问题
public class Foo<T>
例如
var fooType = typeof(Foo<string>);
Console.WriteLine(fooType.Name);
Console.WriteLine(nameof(Foo<string>));
输出
Foo`1
Foo
在许多情况下,您将使用nameof()
Console.WriteLine(nameof(int)); //CS1525 Invalid expression term 'int'
备注
因为自变量需要语法上的表达,所以 列出了许多没有用的东西。下列 值得一提的是会产生错误