繁体   English   中英

如何在C#中创建自定义对象类型类?

[英]How do I create a custom Object type class in C#?

我遇到的情况是,我有几个类具有某些共同点和独特点。 我想创建一个类型比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 
}

我想创建一个类似的类:

class MyObject
{
   string common1;
   string common2;

   //Code Here 
}

这样我创建类似:

Dictionary<int, MyObject>

那将保存MyType1或MyType2,但不保存字符串或int或任何其他字典将保存的内容。 在那里存储的MyObjects将需要能够稍后重铸到MyType1或MyType2,以访问下面的唯一属性。

如果我可以不重铸而访问MyObject.common1或MyObject.common2,那也将是非常不错的。

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM