2

が与えられた場合System.Object、それが持つ可能性のあるメンバーにアクセスするための動的オブジェクトを取得するにはどうすればよいですか。

具体的には、.NET を返す ASP.NET MVC 3 コントローラー アクションを単体テストしたいと考えていますJsonResultJsonResultには type のプロパティDataがありますobject。このオブジェクトに匿名型を設定しています。

return Json(new { Success = "Success" });

私のテストでは、次のようなことをしたい

var result = controller.Foo();

Assert.That(((SomeDynamicType)result.Data).Success, Is.EqualTo("Success"));

これはどのように行われますか?

更新
タイプresult.Dataはですがobject、[ウォッチ] ウィンドウで調べると、次のタイプがあることがわかります。

{
    Name = "<>f__AnonymousType6`1" 
    FullName = "<>f__AnonymousType6`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
} 
System.Type {System.RuntimeType}
4

3 に答える 3

3

匿名型は内部型であり、動的APIは、その保護を尊重するような方法でコンパイラーによって呼び出されます。nugetで利用可能なオープンソースであるImpromptuInterfaceを使用すると、匿名型をラップできるImpromptuGetクラスがあり、匿名型自体からのように動的APIを使用するため、保護の問題は発生しません。

//using ImpromptuInterface.Dynamic
Assert.That(ImpromptuGet.Create(result.Data).Success, Is.EqualTo("Success"));
于 2011-09-01T12:41:08.167 に答える
1

次の実装を使用できますDynamicObject

public class MyDynamic: DynamicObject
{
    private readonly Dictionary<string, object> dictionary = new Dictionary<string, object>();

    public MyDynamic(object initialData)
    {
        if (initialData == null) throw new ArgumentNullException("initialData");
        var type = initialData.GetType();
        foreach (var propertyInfo in type.GetProperties())
        {
            dictionary.Add(propertyInfo.Name, propertyInfo.GetValue(initialData, null));
        }
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        dictionary.TryGetValue(binder.Name, out result);
        return true;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        dictionary[binder.Name] = value;
        return true;
    }

}

その後:

    public void MyTest()
    {
        var json = new {Success = "Ok"};
        dynamic dynObj = new MyDynamic(json);
        Assert.AreEqual(dynObj.Success, "Ok");
    }
于 2013-06-04T17:30:16.320 に答える
-1

Json であるオブジェクトを検査しようとしているので、JsonValueProviderFactory を介して result.Data を実行し、バッキング ストアで「Success」という名前のキーを検索してみませんか?

于 2011-08-31T23:16:40.740 に答える