C# 6 - The nameof Operator
نویسنده: سیروان عفیفی
تاریخ: ۱۳۹۴/۰۷/۱۲ ۱۲:۲۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public static void DoWork(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
} public static void DoWork(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
}
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
} OnPropertyChanged(nameof(Name));
nameof(f()); // where f is a method - you could use nameof(f) instead
nameof(c._Age); // where c is a different class and _Age is private. Nameof can't break accessor rules.
nameof(List<>); // List<> isn't valid C# anyway, so this won't work
nameof(default(List<int>)); // default returns an instance, not a member
nameof(int); // int is a keyword, not a member- you could do nameof(Int32)
nameof(x[2]); // returns an instance using an indexer, so not a member
nameof("hello"); // a string isn't a member
nameof(1 + 2); // an int isn't a member
[MyAttr(nameof(parameter))]
void Method(string parameter)
{
} [MyAttr(nameof(T))]
void Method<T>()
{
} void Method([MyAttr(nameof(parameter))] int parameter)
{
} [return: NotNullIfNotNull(nameof(path))]
public static string? GetUrl(string? path)
=> !string.IsNullOrEmpty(path) ? $"https://localhost/api/{path}" : null; public class NameofClass
{
public string SomeProperty { get; set; }
// Now legal with C# 12
// would show "Length" on the console
public const string NameOfSomePropertyLength = nameof(SomeProperty.Length);
public static int StaticField;
public const string NameOfStaticFieldMinValue = nameof(StaticField.MinValue);
[Description($"String {nameof(SomeProperty.Length)}")]
public int StringLength(string s)
{
return s.Length;
}
}