初始化要用作类型的某个实例的动态对象
本文关键字:实例 动态 对象 初始化 类型 | 更新日期: 2023-09-27 18:33:33
复制:
片段 1:
class A{
A(int i){}
A(string s){}
A(Form b){}
A(Stream b){}
//...more constructors but no one accepts object type
}
片段 2:
A assign(object obj)
{
dynamic d=obj;
//do something with d or obj?
A a=new A(d);
return a;
}
如何使生产线A a=new A(d);
工作?
编辑:
如何在没有动态类型机制的情况下使线路A a=new A(d);
工作?
Add A(object obj){}
对于 A 的构造函数,然后使用 GetType() 来标识它。
public A(object obj)
{
if(obj is int)
//Do something with the int.
if(obj is string)
//Do something with the string.
if(obj is Form)
//Do something with the Form.
//etc...
}