gpt4 book ai didi

C# 通过引用传递属性

转载 作者:IT王子 更新时间:2023-10-29 04:26:52 26 4
gpt4 key购买 nike

有没有办法通过引用传递对象的属性?我知道我可以传递整个对象,但我想指定要设置的对象属性并检查它的类型,以便我知道如何解析。我是否应该采取另一种方法(无论如何我都无法更改原始对象)?

public class Foo{
public Foo(){}
public int Age { get; set; }
}

private void setFromQueryString(object aProperty, String queryString, HttpContext context)
{
//here I want to handle pulling the values out of
//the query string and parsing them or setting them
//to null or empty string...
String valueString = context.Request.QueryString[queryString].ToString();

//I need to check the type of the property that I am setting.

//this is null so I can't check it's type
Type t = aProperty.GetType();
}

private void callingMethod(HttpContext context)
{
Foo myFoo = new Foo();
setFromQueryString(myFoo.Age, "inputAge", context);
}

最佳答案

您可以使用 lambda 表达式调用该函数:

private void setFromQueryString<T>(Action<T> setter, String queryString, HttpContext context) 
{
//here I want to handle pulling the values out of
//the query string and parsing them or setting them
//to null or empty string...
String valueString = context.Request.QueryString[queryString].ToString();

//I need to check the type of the property that I am setting.

//this is null so I can't check it's type
Type t = typeof(T);
...
setter(value);
}

你可以这样调用它:

setFromQueryString<int>(i => myFoo.Age = i, "inputAge", context);

编辑:如果您真的想要类型推断:

private void setFromQueryString<T>(Func<T> getter, Action<T> setter, String queryString, HttpContext context) {
...
}
setFromQueryString(() => myFoo.Age, i => myFoo.Age = i, "inputAge", context);

关于C# 通过引用传递属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2374963/

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