gpt4 book ai didi

c# - 确定方法参数的上下文

转载 作者:太空狗 更新时间:2023-10-30 00:42:26 25 4
gpt4 key购买 nike

这是一个具有挑战性的问题。是否可以使用任何方法隐式确定作为参数传递给方法的属性的名称?

(乍一看这似乎是另一个问题的重复,但有一个微妙但重要的不同之处在于我们总是使用属性,这是关键)。

这是示例场景:

    public class Foo
{
public string Bar { get; set; }
}

public void SomeStrangeMethod()
{
Foo foo = new Foo() { Bar = "Hello" };
string result = FindContext(foo.Bar); // should return "Bar"
}

public string FindContext(object obj)
{
// TODO? - figure out the property name corresponding to the passed parameter.
// In this example, we need to somehow figure out that the value of "obj"
// is the value of the property foo.Bar, and return "Bar"
}

假设在 FindContext 中,传递的参数将始终是对象的属性。问题是,我们不知道是什么对象。

显然,通过传递提供缺失上下文的第二个参数可以轻松解决问题,即...

FindContext(foo, foo.Bar);    
FindContext("Bar", foo.Bar);

....但这不是我想要的。我希望能够传递单个参数并确定该值表示的属性名称。

据我所知,传递参数时,FindContext 的方法上下文不包含足够的信息来确定这一点。然而,使用一些围绕堆栈跟踪和 IL 的花招,也许我们仍然可以做到。我认为这一定是可能的原因是:

  1. 要求传递给 FindContext 的参数必须始终是另一个对象的属性,我们知道可以使用反射获取所述属性名称。

  2. 使用 StackTrace,我们可以获得调用上下文。

  3. 在调用上下文之外,我们应该能够以某种方式找到正在使用的符号。

  4. 从该符号中,我们应该能够检索属性名称和/或调用对象的类型,通过 (1) 我们应该能够将其转换为调用对象的属性。

有人知道怎么做吗?注:这道题很难,但我不相信做不到。除非有人能证明为什么不可能,否则我不会接受任何“不可能”的答案。

最佳答案

如果你传递一个lambda表达式你可以

public class Foo
{
public string Bar { get; set; }
}

public void SomeStrangeMethod()
{
Foo foo = new Foo() { Bar = "Hello" };
string result = GetName(()=>foo.Bar); // should return "Bar"
Debug.WriteLine(result); // "Bar"
}


public static string GetName<T>(Expression<Func<T>> expression)
{
return ExtractPropertyName(expression);
}

/// <summary>
/// Extracts the name of a property from a suitable LambdaExpression.
/// </summary>
/// <param name="propertyExpression">The property expression.</param>
/// <returns></returns>
public static string ExtractPropertyName(LambdaExpression propertyExpression)
{
if (propertyExpression == null)
{
throw new ArgumentNullException("propertyExpression");
}

var memberExpression = propertyExpression.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException(@"Not a member expression", "propertyExpression");
}

var property = memberExpression.Member as PropertyInfo;
if (property == null)
{
throw new ArgumentException(@"Not a property", "propertyExpression");
}

var getMethod = property.GetGetMethod(true);
if (getMethod.IsStatic)
{
throw new ArgumentException(@"Can't be static", "propertyExpression");
}

return memberExpression.Member.Name;
}

关于c# - 确定方法参数的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15527970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com