让我用下面的例子来解释我的问题:
public string ExampleFunction(string Variable) {
return something;
}
string WhatIsMyName = "Hello World"';
string Hello = ExampleFunction(WhatIsMyName);
Run Code Online (Sandbox Code Playgroud)
当我将变量"WhatIsMyName"传递给示例函数时,我希望能够获取原始变量名称的字符串.也许是这样的:
Variable.OriginalName.ToString()
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
你们都这样做了:
public void Proc(object parameter)
{
if (parameter == null)
throw new ArgumentNullException("parameter");
// Main code.
}
Run Code Online (Sandbox Code Playgroud)
Jon Skeet曾经提到他有时会使用扩展来进行检查,所以你可以这样做:
parameter.ThrowIfNull("parameter");
Run Code Online (Sandbox Code Playgroud)
所以我得到了这个扩展的两个实现,我不知道哪个是最好的.
第一:
internal static void ThrowIfNull<T>(this T o, string paramName) where T : class
{
if (o == null)
throw new ArgumentNullException(paramName);
}
Run Code Online (Sandbox Code Playgroud)
第二:
internal static void ThrowIfNull(this object o, string paramName)
{
if (o == null)
throw new ArgumentNullException(paramName);
}
Run Code Online (Sandbox Code Playgroud)
你怎么看?
更新:这不再是来自C#6的问题,它引入了
nameof
运营商来解决这些问题(参见MSDN).注意:有关此问题的一般化以及一些答案,请参阅" 在运行时通过lambda表达式获取局部变量(和参数)的名称 ".
我喜欢使用lambda表达式创建INotifyPropertyChanged
接口的重构安全实现的想法,使用类似于Eric De Carufel提供的代码.
我正在尝试实现类似的东西ArgumentException
,以重构安全的方式为(或其派生类)提供参数名称.
我已经定义了以下实用程序方法来执行null
检查:
public static void CheckNotNull<T>(Expression<Func<T>> parameterAccessExpression)
{
Func<T> parameterAccess = parameterAccessExpression.Compile();
T parameterValue = parameterAccess();
CheckNotNull(parameterValue, parameterAccessExpression);
}
public static void CheckNotNull<T>(T parameterValue,
Expression<Func<T>> parameterAccessExpression)
{
if (parameterValue == null)
{
Expression bodyExpression = parameterAccessExpression.Body;
MemberExpression memberExpression = bodyExpression as MemberExpression;
string parameterName = memberExpression.Member.Name;
throw new ArgumentNullException(parameterName);
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以使用以下语法以重构安全的方式执行参数验证:
CheckNotNull(() => arg); // most concise
CheckNotNull(arg, …
Run Code Online (Sandbox Code Playgroud)