我正在寻找类似于 objective-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;
}
...
我如何在 C# 中做同样的事情? 谢谢, 尼克尔。
最佳答案
您可以通过两种方式做到这一点:
首先,您可以将类型声明为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;
} // ...
第二个选项需要 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();
} // ...
关于c# - 在c#中声明一个可以是任何类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4684444/