2

私は(文字列、オブジェクト)辞書を持っています。オブジェクト(クラス)には、列挙型で定義されたデータ型を含むいくつかの値があります。辞書項目の値を返す GetItemValue メソッドが必要です。したがって、戻り値の型は item オブジェクトで定義された型でなければなりません。

Class Item
{
    String Name;
    DataValueType DataType;
    Object DataValue;
}

private Dictionary<string, Item> ItemList = new Dictionary<string, Item>();

void Main()
{
    int value;

    ItemList.Add("IntItem", new Item("IntItem", DataValueType.TInt, 123));
    value = GetItemValue("IntItem"); // value = 123
}

この問題を克服できるソリューションはどのようなものでしょうか?

よろしくお願いします、

4

4 に答える 4

2

より良い解決策は、すべてのクラスに実装させるインターフェイスを導入することです。インターフェイスは必ずしも動作を指定する必要はないことに注意してください。

public interface ICanBePutInTheSpecialDictionary {
}

public class ItemTypeA : ICanBePutInTheSpecialDictionary {
    // code for the first type
}

public class ItemTypeB : ICanBePutInTheSpecialDictionary {
    // code for the second type
}
// etc for all the types you want to put in the dictionary

辞書に入れるには:

var dict = new Dictionary<string, ICanBePutInTheSpecialDictionary>();

dict.add("typeA", new ItemTypeA());
dict.add("typeB", new ItemTypeB());

オブジェクトを特定のタイプにキャストする必要がある場合は、次のような --block をif使用できます。elseif

var obj = dict["typeA"];
if (obj is ItemTypeA) {
    var a = obj as ItemTypeA;
    // Do stuff with an ItemTypeA. 
    // You probably want to call a separate method for this.
} elseif (obj is ItemTypeB) {
    // do stuff with an ItemTypeB
}

またはリフレクションを使用します。選択肢の数に応じて、どちらかが望ましい場合があります。

于 2013-04-07T15:36:36.373 に答える
0

「混合バッグ」がある場合、次のようなことができます...

class Item<T>
{
    public String Name { get; set; }
    public DataValueType DataType { get; set; }
    public T DataValue { get; set; }
}
class ItemRepository
{
    private Dictionary<string, object> ItemList = new Dictionary<string, object>();

    public void Add<T>(Item<T> item) { ItemList[item.Name] = item; }
    public T GetItemValue<T>(string key)
    {
        var item = ItemList[key] as Item<T>;
        return item != null ? item.DataValue : default(T);
    }
}

そしてそれを次のように使用します...

var repository = new ItemRepository();
int value;
repository.Add(new Item<int> { Name = "IntItem", DataType = DataValueType.TInt, DataValue = 123 });
value = repository.GetItemValue<int>("IntItem");

いくつかのタイプしかない場合は、Repository<T>.

于 2013-04-07T16:20:29.900 に答える