声明一个可以是c#中任何类型的对象

Nik*_*kil 1 c# oop

我正在寻找一个类似于目标c中类型'id'的实现,它可以在运行时使用任何类型.是否可以在c#中执行此操作?

让我解释一下我的要求

id abc;// a common type which can hold any object during runtime
if(cond1)
{
 Option1 opt1 = new Option1();//opt1 is an object of user defined class Option1
 abc = opt1;
}
else if(cond2)
{
 Option2 opt2 = new Option2();
 abc = opt2;
}
...
Run Code Online (Sandbox Code Playgroud)

我怎样才能在c#中做同样的事情?谢谢,Nikil.

Ree*_*sey 10

您可以通过两种方式执行此操作:

首先,您可以将类型声明为object.这将允许您为该类型分配任何内容.但请注意,如果为对象引用指定值类型,则会将其装箱.

例如:

object abc;
if(cond1)
{
 Option1 opt1 = new Option1();//opt1 is an object of user defined class Option1
 // Assignment works, but you can't call a method or prop. defined on Option1
 abc = opt1;
} // ...
Run Code Online (Sandbox Code Playgroud)

第二个选项,需要C#4,将其声明为dynamic.这将允许您实际调用对象上的方法和属性,就像它是"真实"类型一样.如果方法调用不存在,则会在运行时失败,但在编译时会成功.

例如:

dynamic abc;
if(cond1)
{
 Option1 opt1 = new Option1();//opt1 is an object of user defined class Option1
 // Assignment works
 abc = opt1;

 // This will work if Option1 has a method Option1Method()!
 // If not, it will raise an exception at run time...
 abc.Option1Method(); 
} // ...
Run Code Online (Sandbox Code Playgroud)