可能重复:
查找传递给C#中函数的变量名称
我想获取变量或参数的名称:
例如,如果我有:
var myInput = "input";
var nameOfVar = GETNAME(myInput); // ==> nameOfVar should be = myInput
void testName([Type?] myInput)
{
var nameOfParam = GETNAME(myInput); // ==> nameOfParam should be = myInput
}
Run Code Online (Sandbox Code Playgroud)
我怎么能在C#中做到这一点?
例如,
static void Main()
{
var someVar = 3;
Console.Write(GetVariableName(someVar));
}
Run Code Online (Sandbox Code Playgroud)
该程序的输出应为:
someVar
Run Code Online (Sandbox Code Playgroud)
如何使用反射实现这一目标?
可能重复:
查找传递给C#中函数的变量名称
下面的课程包含现场城市.
我需要动态确定字段名称,因为它是在类声明中输入的,即我需要从对象城市的实例中获取字符串"city".
我试图通过检查其在DoSomething()中的类型来做到这一点,但在检查调试器中的Type的内容时找不到它.
可能吗?
public class Person
{
public string city = "New York";
public Person()
{
}
public void DoSomething()
{
Type t = city.GetType();
string field_name = t.SomeUnkownFunction();
//would return the string "city" if it existed!
}
}
Run Code Online (Sandbox Code Playgroud)
下面他们的答案中的一些人问我为什么要这样做.这就是原因.
在我的真实世界中,城市上方有一个自定义属性.
[MyCustomAttribute("param1", "param2", etc)]
public string city = "New York";
Run Code Online (Sandbox Code Playgroud)
我需要在其他代码中使用此属性.要获取属性,我使用反射.在反射代码中我需要输入字符串"city"
MyCustomAttribute attr;
Type t = typeof(Person);
foreach (FieldInfo field in t.GetFields())
{
if (field.Name == "city")
{
//do stuff when we find the field that has …Run Code Online (Sandbox Code Playgroud) 可能重复:
查找传递给C#中函数的变量名称
在C#中,有没有办法(更好的方法)在运行时解析参数的名称?
例如,在以下方法中,如果重命名方法参数,则还必须记住更新传递给ArgumentNullException的字符串文字.
public void Woof(object resource)
{
if (resource == null)
{
throw new ArgumentNullException("resource");
}
// ..
}
Run Code Online (Sandbox Code Playgroud) 我有兴趣以重构安全的方式在运行时检索局部变量(和参数)的名称.我有以下扩展方法:
public static string GetVariableName<T>(Expression<Func<T>> variableAccessExpression)
{
var memberExpression = variableAccessExpression.Body as MemberExpression;
return memberExpression.Member.Name;
}
Run Code Online (Sandbox Code Playgroud)
...返回通过lambda表达式捕获的变量的名称:
static void Main(string[] args)
{
Console.WriteLine(GetVariableName(() => args));
// Output: "args"
int num = 0;
Console.WriteLine(GetVariableName(() => num));
// Output: "num"
}
Run Code Online (Sandbox Code Playgroud)
但是,这只能起作用,因为C#编译器将在匿名函数中捕获的任何局部变量(和参数)提升为幕后编译器生成的类中的同名实例变量(每个Jon Skeet).如果不是这种情况,则转换为Bodyto MemberExpression会失败,因为MemberExpression代表字段或属性访问.
这个变量是促销记录的行为,还是一个实现细节可能会在框架的其他版本中发生变化?
注意:这个问题是我前一个关于参数验证的概括.
你们都这样做了:
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)
你怎么看?
我有一个扩展方法进行测试,所以我可以这样做:
var steve = new Zombie();
steve.Mood.ShouldBe("I'm hungry for brains!");
Run Code Online (Sandbox Code Playgroud)
扩展方法:
public static void ShouldBe<T>(this T actual, T expected)
{
Assert.That(actual, Is.EqualTo(expected));
}
Run Code Online (Sandbox Code Playgroud)
由此可见:
Expected: "I'm hungry for brains!"
But was: "I want to shuffle aimlessly"
Run Code Online (Sandbox Code Playgroud)
是否有任何黑客可以从我的扩展方法中获取属性"BrainsConsumed"的名称?奖励积分将是实例变量并输入Zombie.
更新:
新的ShouldBe:
public static void ShouldBe<T>(this T actual, T expected)
{
var frame = new StackTrace(true).GetFrame(1);
var fileName = frame.GetFileName();
var lineNumber = frame.GetFileLineNumber() - 1;
var code = File.ReadAllLines(fileName)
.ElementAt(lineNumber)
.Trim().TrimEnd(';');
var codeMessage = new Regex(@"(^.*)(\.\s*ShouldBe\s*\()([^\)]+)\)").Replace(code, @"$1 should be $3");
var actualMessage …Run Code Online (Sandbox Code Playgroud) 我有一个方法,我想转换为扩展方法
public static string GetMemberName<T>(Expression<Func<T>> item)
{
return ((MemberExpression)item.Body).Member.Name;
}
Run Code Online (Sandbox Code Playgroud)
并称之为
string str = myclass.GetMemberName(() => new Foo().Bar);
Run Code Online (Sandbox Code Playgroud)
所以评估为 str = "Bar"; // It gives the Member name and not its value
现在,当我尝试将此转换为扩展方法时
public static string GetMemberName<T>(this Expression<Func<T>> item)
{
return ((MemberExpression)item.Body).Member.Name;
}
Run Code Online (Sandbox Code Playgroud)
并称之为
string str = (() => new Foo().Bar).GetMemberName();
Run Code Online (Sandbox Code Playgroud)
错误说 Operator '.' cannot be applied to operand of type 'lambda expression'
我哪里错了?
我有变数
public string MyVariable;
Run Code Online (Sandbox Code Playgroud)
我需要使用变量名作为字符串.例:
var a = MyVariable.NameVariable();
// a = "MyVariable"
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
我想创建你的miniORM(NHibernate太重了,需要一个单独的库).目前问题是我必须指出一堆常量.例如:
public const string FieldIdRules = "idRules"
Run Code Online (Sandbox Code Playgroud)
然后在samonapisannom profiler中进行交易.我看到Hibernate不需要指定文本值(对于字段的比例).我想实现同样的目标.
对不起我的英文不好
我正在 C# 8 中试验 [CallerArgumentExpression]:
static void Main(string[] args)
{
try
{
Program query = null;
Argument(query != null, "Ooops");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static void Argument(bool condition, string message, [CallerArgumentExpression("condition")] string conditionExpression = null)
{
if (!condition) throw new ArgumentException(message: message, paramName: conditionExpression);
}
Run Code Online (Sandbox Code Playgroud)
但是,我无法将 的值conditionExpression设为 null 以外的任何值。
我一直在使用这个https://blog.mcilreavy.com/articles/2018-08/caller-argument-expression-attribute和其他一些页面,当然,作为指南很好,但我无法得到让它工作。