2

共通点と独自性を持つクラスがいくつかある状況があります。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 のいずれかを保持しますが、string や int など、辞書が保持するものは保持しません。そこに格納されている MyObjects は、後で MyType1 または MyType2 に再キャストして、その下にある固有の属性にアクセスできるようにする必要があります。

また、MyObject.common1 または MyObject.common2 に再キャストせずにアクセスできれば、本当に素晴らしいことです。

4

1 に答える 1

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
}
于 2011-01-17T05:40:43.357 に答える