【解決方法】オブジェクトを辞書にキャストするにはどうすればよいですか?


オブジェクトを辞書にキャストするにはどうすればよいですか?

ディクショナリのキーと値は任意の型にすることができます。

私が試したこと:

C#
public class Example {

    void CallMethod () {
        SomeMethod (new Dictionary<string, bool> ());
        SomeMethod (new Dictionary<int, long> ());
        SomeMethod<Dictionary<string, bool>> (new Dictionary<string, bool> ());
    }
    
    void SomeMethod (object value) {
        var dic = value as Dictionary<,>;
        // What is type of Dictionary key or value?
    }

    void SomeMethd<T> (T value) {
        // T can be Dictionary, int, bool, List, ...
        if (value is Dictionary) {
            // T is dictionary, but we don't know type of key and value
            // How do i cast it to dictionary?
            var dic = value as Dictionary<,>;
            foreach (var item in dic) {
                
            }
        }
    }

    T SomeMethod<T> () {
        // I want to load the dictionary here
        if (typeof(T) is IDictionary) {
            // Now, what is type of the key and value?
            IDictionary dic = new Dictionary<,> ();
            int count = 1;
            for (int i = 0; i < count; i++) {
                dic.Add (SomeMethod<Type of Key> (), SomeMethod<Type of value> ());
            }
            // Throws an exception
            return dic;
        }
        return default(T);
    }
    
}

解決策 2

ディクショナリの型 (キーと値を意味する) を知っていない限り、それを行う唯一の方法はそれを Dictionary にキャストすることです。これは非常に悪い考えです。 C# を非常に堅牢にします。 この時点で、作成した辞書を使用するためにランタイム キャストに依存していますが、これはお粗末な考えです。

代わりに Generics を使用することを検討したので、Dictionary をキャストする必要はありません。メソッドを呼び出すときに型が推測されますか?

void SomeMethod<K, V>(Dictionary<K, V> dict)
    {
    ///...
    }

これにより、コードがより堅牢になり、読みやすくなります。

解決策 3

タイプ情報があなたにとってどの程度重要であるかに応じて SomeMethod() あなたができる方法:

C#
// minimal type info needed
void SomeMethod (System.Collections.IDictionary dictionary)
{
   foreach(var k in dictionary.Keys)
   {
      // k and dictionary[k] as value
   }
}

または、型が必要な場合:

C#
// overloaded for each case
void SomeMethod (System.Collections.Generic.Dictionary<int,long> dictionary)
{
   foreach(var kv in dictionary)
   {
      //access to kv.Key and kv.Value as int and long
   }
}

void SomeMethod (System.Collections.Generic.Dictionary<string,bool> dictionary)
{
   foreach(var kv in dictionary)
   {
      //access to kv.Key and kv.Value as string and bool
   }
}

解決策 4

これはとても簡単です:

C#
void SomeMethod (object value) {
    var dic = value as IDictionary;
    Type dicType = dic.GetType();
    Type[] argTypes = dicType.GetGenericTypeDefinition().GetGenericArguments();
    Type keyType = argTypes[0];
    Type valueType = argTypes[1];
    foreach (var pair in dict) {
    	// ...
    }
}

解決策 1

うまくいけば、私は質問を正しく受けました。 辞書に異議を唱える。 エラーなく実行されます。

var dic = value as Dictionary<object,object>;

コメント

タイトルとURLをコピーしました