C# 在对象中使用方法参数作为引用
我正在从SQL数据库返回一个名为AllCodes的代码列表。基本模式,如:C# 在对象中使用方法参数作为引用,c#,asp.net,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc 4,我正在从SQL数据库返回一个名为AllCodes的代码列表。基本模式,如: id | countrycode | refprint | refscan | reffax 1 . US . 123 . 234 . 345 我有一个方法,它需要返回一个基于匹配countrycode的值,以及我从结果中需要的任何列 下面是一个方法(不正常工作),但不确定如何用c实现这种事情# 您可以通过反射来实现这一点: if (code != null) { PropertyInfo pi = code
id | countrycode | refprint | refscan | reffax
1 . US . 123 . 234 . 345
我有一个方法,它需要返回一个基于匹配countrycode的值,以及我从结果中需要的任何列
下面是一个方法(不正常工作),但不确定如何用c实现这种事情#
您可以通过反射来实现这一点:
if (code != null)
{
PropertyInfo pi = code.GetType().GetProperty(name);
if (pi == null) return string.Empty;
object v = pi.GetValue(code);
if (v == null) return string.Emtpy;
return v.ToString();
}
使用GetProperty()
可以为名为name
的属性获取PropertyInfo
。然后,您可以使用GetValue()
获取特定实例的属性值(code
)
在C#6中,您可以将代码缩短为
return code.GetType().GetProperty(name)?.GetValue(code)?.ToString() ?? string.Empty;
您可以通过反射来实现这一点:
if (code != null)
{
PropertyInfo pi = code.GetType().GetProperty(name);
if (pi == null) return string.Empty;
object v = pi.GetValue(code);
if (v == null) return string.Emtpy;
return v.ToString();
}
使用GetProperty()
可以为名为name
的属性获取PropertyInfo
。然后,您可以使用GetValue()
获取特定实例的属性值(code
)
在C#6中,您可以将代码缩短为
return code.GetType().GetProperty(name)?.GetValue(code)?.ToString() ?? string.Empty;
使用lambda怎么样:
private string GetServiceCode<T>(string cc, Action<T> action)
{
var code = AllCodes.Where(x => x.CountryCode == cc).FirstOrDefault();
if (code != null)
{
return action(code);
}
}
// Example:
GetServiceCode("US",(code)=> Console.WriteLine(code.refprint) );
私有字符串GetServiceCode(字符串cc,操作)
{
var code=AllCodes.Where(x=>x.CountryCode==cc.FirstOrDefault();
如果(代码!=null)
{
返回动作(代码);
}
}
//例如:
GetServiceCode(“US”,(code)=>Console.WriteLine(code.refprint));
使用lambda怎么样:
private string GetServiceCode<T>(string cc, Action<T> action)
{
var code = AllCodes.Where(x => x.CountryCode == cc).FirstOrDefault();
if (code != null)
{
return action(code);
}
}
// Example:
GetServiceCode("US",(code)=> Console.WriteLine(code.refprint) );
私有字符串GetServiceCode(字符串cc,操作)
{
var code=AllCodes.Where(x=>x.CountryCode==cc.FirstOrDefault();
如果(代码!=null)
{
返回动作(代码);
}
}
//例如:
GetServiceCode(“US”,(code)=>Console.WriteLine(code.refprint));
你可以看-然后是。选择(名称)
你说列表,但你真的在使用字典吗?你可以看-然后是。选择(名称)
你说列表,但你真的在使用字典吗?