我有一种情况,我有几个有共同点的东西和有些独特的东西.我想创建一个比object []更强类型的类,但可以保存任何其他类.
如果我有例如:
class MyType1
{
string common1;
string common2;
string type1unique1;
string type1unique2;
//Constructors Here
}
class MyType2
{
string common1;
string common2;
string type2unique1;
string type2unique2;
//Constructors Here
}
Run Code Online (Sandbox Code Playgroud)
我想创建一个类如下的类:
class MyObject
{
string common1;
string common2;
//Code Here
}
Run Code Online (Sandbox Code Playgroud)
所以我创建了类似的东西:
Dictionary<int, MyObject>
Run Code Online (Sandbox Code Playgroud)
这将包含MyType1或MyType2,但不包含字符串或int或字典将保存的任何其他内容.存储在那里的MyObjects需要能够稍后重铸到MyType1或MyType2以访问下面的唯一属性.
如果我可以访问MyObject.common1或MyObject.common2而不重铸它,那将是非常好的.
dje*_*eeg 14
public abstract class MyObject {
protected string common1;
protected string common2;
}
public class MyType1 : MyObject {
string type1unique1;
string type1unique2;
}
public class MyType2 : MyObject {
string type2unique1;
string type2unique2;
}
IDictionary<int, MyObject> objects = new Dictionary<int, MyObject>();
objects[1] = new MyType1();
objects[1].common1
if(objects[1] is MyType1) {
((MyType1)objects[1]).type1unique1
}
Run Code Online (Sandbox Code Playgroud)