Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/478.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#基于GetType()的返回值动态强制转换对象_C# - Fatal编程技术网

C#基于GetType()的返回值动态强制转换对象

C#基于GetType()的返回值动态强制转换对象,c#,C#,我对C#的编码还很陌生,我正在“深入”这个问题 检查类型并将其转换为与相同的类型。如果项目不是A,则as将返回null,因此您可以使用合并运算符(?)来确定要输出的内容 foreach (var item in b.GetType().GetProperties()) { object rawValue = item.GetValue(b); A typedValue = rawValue as A; string output = (typedValue?.AA ??

我对C#的编码还很陌生,我正在“深入”这个问题 检查类型并将其转换为与
相同的类型。如果项目不是A,则
as
将返回
null
,因此您可以使用合并运算符(
)来确定要输出的内容

foreach (var item in b.GetType().GetProperties())
{
    object rawValue = item.GetValue(b);
    A typedValue = rawValue as A;
    string output = (typedValue?.AA ?? rawValue).ToString();
    Console.WriteLine("Name:{0}  Value:{1}", output );

}
或者(这可能更容易理解):

还是像这样

static void Main(字符串[]args)
{
A=新A(){a1=11,a2=22,a3=33};
C=新的C(){c1=111,c2=222,c3=333};
B=新的B(){b1=a,b2=c,b3=1};
//遍历b的属性
foreach(b.GetType().GetProperties()中的变量项)
{
var d=b.GetType().GetProperty(item.Name);
var e=d.GetValue(b);
//这里我们迭代a和c的属性(从b对象)
//它将动态打印其属性
foreach(e.GetType().GetProperties()中的变量f)
{
WriteLine(“Name:{0}值:{1}”,f.Name,f.GetValue(e));
}
}
Console.ReadLine();
}
甲级
{
公共int a1{get;set;}
公共int a2{get;set;}
公共int a3{get;set;}
}
B类
{
公共A b1{get;set;}
公共C b2{get;set;}
公共int b3{get;set;}
}
C类
{
公共int c1{get;set;}
公共int c2{get;set;}
公共int c3{get;set;}
}
产出:

名称:a1值:11
名称:a2值:22
名称:a3值:33
名称:c1值:111
名称:c2值:222
名称:c3值:333

我的问题中缺少了答案部分“但在我的实际代码中,这可能是几个类的选择”。如果
A
(如本问题中的示例)可能是许多不同的类中的任何一个,那么这对编程来说将是可怕的。。。。。你问过演员的问题。根据定义,除非为强制转换编写特定于类型的代码,否则无法强制转换。如果有许多可能的类型,这就是为什么。没错,“演员”一词是问题的主题。我认为另一个答案(我标记为答案)将解决我的问题。谢谢你的输入!看起来很简单,谢谢。。。。。现在我必须弄清楚我是否可以把这个应用到我的真实代码中!
foreach (var item in b.GetType().GetProperties())
{
    object rawValue = item.GetValue(b);
    A typedValue = rawValue as A;
    if (typedValue == null)
    {
        Console.WriteLine("Name:{0} Value:{1}", rawValue);
    }
    else
        Console.WriteLine("Name:{0} Value:{1}", typedValue.AA);
    }
}