Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在对象中使用方法参数作为引用_C#_Asp.net_Asp.net Mvc 4 - Fatal编程技术网

C# 在对象中使用方法参数作为引用

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

我正在从SQL数据库返回一个名为AllCodes的代码列表。基本模式,如:

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));

你可以看-然后是
。选择(名称)
你说列表,但你真的在使用字典吗?你可以看-然后是
。选择(名称)
你说列表,但你真的在使用字典吗?