2011-01-17 9 views
1

私は共通して一生懸命にしているいくつかのクラスを持っている状況があります。オブジェクト[]よりも厳密に型指定されたクラスを作成したいと思いますが、これらのクラスを保持することができます。C#でカスタムオブジェクト型クラスを作成するにはどうすればよいですか?

私は例えばお持ちの場合:

Dictionary<int, MyObject> 

:私はのようなものを作るようにするため

class MyObject 
{ 
    string common1; 
    string common2; 

    //Code Here 
} 

class MyType1 
{ 
    string common1; 
    string common2; 
    string type1unique1; 
    string type1unique2; 

    //Constructors Here 
} 

class MyType2 
{ 
    string common1; 
    string common2; 
    string type2unique1; 
    string type2unique2; 

    //Constructors Here 
} 

私のようなクラスのものを作成したいのですがMyType1またはMyType2のいずれかを保持するが、文字列またはintまたは辞書が保持するその他のものは保持しない。そこに格納されているMyObjectsは、後でMyType1またはMyType2に再作成して、その下の一意の属性にアクセスできる必要があります。

また、私がMyObject.common1またはMyObject.common2にアクセスすることができれば、本当に素晴らしいことでしょう。

+2

素晴らしい計画のようですが、あなたは正確に質問しませんでした。 –

+0

標準継承で何が問題になっていますか? – Cameron

+1

既にStackOverflowでこれをカバーする多くの質問があります。たとえば、[this search](http://stackoverflow.com/search?q= [c%23] + inheritance + base + class)を確認してください。 10分をかけて、これらの質問の選択肢を読んでください。 – slugster

答えて

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 
} 
+0

ちょうどこの答えに追加する....「MyObject」のようなものを「MyBaseObject」と命名し、抽象的にすることを検討してください。 – slugster

関連する問題