タイプ String、UnknownClass のディクショナリに格納されているオブジェクトにアクセスしようとしています。私はキーを持っており、その値がいくつかのコンテナー クラスの 1 つであることを知っています。値はオブジェクトを取るメソッドに渡されるため、値として格納されているクラスの型を知る必要はありません。また、キーが存在することを確認するために、ContainsKey を呼び出す必要があります。
次の方法を試しましたが、成功しませんでした。
Dictionary<String, object> list = (Dictionary<String, object>)source.GetType().GetProperty(dictionaryName).GetValue(source, null);
nextSource = list[key];
これにより、キャストエラーが発生し、次のようになります。
nextSource = source.GetType().GetMethod("get_Item").Invoke(source, new object[] { key });
これにより、null参照例外が発生します。
ここにもう少しコードを示しますが、これが役立つかどうかはよくわかりません。
private void SetValue(object source, String path, String value)
{
if (path.Contains('.'))
{
// If this is not the ending Property, continue recursing
int index = path.IndexOf('.');
String property = path.Substring(0, index);
object nextSource;
if(property.Contains("*"))
{
path = path.Substring(index + 1);
index = path.IndexOf('.');
String dictionaryName = path.Substring(0, index);
Dictionary<String, object> list = (Dictionary<String, object>)source.GetType().GetProperty(dictionaryName).GetValue(source, null);
nextSource = list[property.Substring(1)];
//property = property.Substring(1);
//nextSource = source.GetType().GetMethod("Item").Invoke(source, new[] { property });
} ...
アクセスされる辞書は、PersonObject クラスで次のように定義されます。
public class PersonObject
{
public String Name { get; set; }
public AddressObject Address { get; set; }
public Dictionary<String, HobbyObject> Hobbies { get; set; }
この段階で、Path の値は に設定され"*Hiking.Hobbies.Hobby"
ます。基本的に、パス文字列を使用すると、サブクラスのプロパティに移動できます。同じクラスのリストのプロパティにアクセスするには、ディクショナリが必要です。