C# 有可能进行动态的向下广播吗?

C# 有可能进行动态的向下广播吗?,c#,downcast,C#,Downcast,如何使用强运行时已知类型进行向下转换 public class A {} public class B : A { public int i; } public class C { B b = new B(); A a = b; // here upcast, and "a" still keeps link to "b" ((B)a).i; // no problem it works Type t =

如何使用强运行时已知类型进行向下转换

public class A {}

public class B : A { public int i; }

public class C
{
    B b = new B();
    A a = b;               // here upcast, and "a" still keeps link to "b"
    ((B)a).i;              // no problem it works

    Type t = b.GetType();  // BUT how to downcast with strongly runtime known type ?
    ((t)a).i;              // like here
}

任何运行时转换的问题,例如使用
Convert.ChangeType
,您只能返回
object
,这意味着如果不使用反射,您将无法执行任何有用的操作(例如设置属性)

“我不知道类型,但我相信我可以设置给定属性”的一种可能性是使用
动态

B b = new B();
A a = b; 
dynamic x = a;
x.i = 100;
Console.WriteLine(b.i); /// writes 100.
实例:

注意:如果尝试调用不存在的属性/方法,则会显示相应的错误:

x.nosuchproperty =  100;
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:'Rextester.B'不包含'nosuchproperty'的定义


任何运行时转换的问题,例如使用
Convert.ChangeType
,您只能返回
object
,这意味着如果不使用反射,您将无法执行任何有用的操作(例如设置属性)

“我不知道类型,但我相信我可以设置给定属性”的一种可能性是使用
动态

B b = new B();
A a = b; 
dynamic x = a;
x.i = 100;
Console.WriteLine(b.i); /// writes 100.
实例:

注意:如果尝试调用不存在的属性/方法,则会显示相应的错误:

x.nosuchproperty =  100;
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:'Rextester.B'不包含'nosuchproperty'的定义


这里有几个铸造语法:VarA=(a)b;var a=(b作为a);因为编译器不知道
t
是什么,所以它不知道成员
i
是否存在。如果您没有对成员进行编译时检查,则可以尝试
动态
…使用
((t)a)进行类型转换
要求在程序运行之前,在编译时已知
t
。在这段代码中,
t
在编译时显然是未知的,因为它是一个在运行时获取其值的变量;var a=(b作为a);因为编译器不知道
t
是什么,所以它不知道成员
i
是否存在。如果您没有对成员进行编译时检查,则可以尝试
动态
…使用
((t)a)进行类型转换
要求在程序运行之前,在编译时已知
t
。在这段代码中,
t
在编译时显然是未知的,因为它是一个在运行时获取其值的变量?NET3.5没有“动态”。很抱歉,但当我只有NET3.5时?NET3.5没有“动态”。