使用多种语言的动态对象时,有一个构造允许您获取属性的值,如果该属性不存在,则返回默认值.
我想知道在.NET中使用dynamic时是否有类似的方法/语法.我知道您可以将ExpandoObject强制转换为Dictionary,但有时无法保证动态对象是Expando.
我正在考虑一些与以下代码具有相同效果的东西
public class SomeClass
{
public string ValidProperty { get; set; }
}
dynamic t = new SomeClass() {
ValidProperty = "someValue"
};
Console.WriteLine(t.Get("ValidProperty", "doesn't exist")); // Prints 'someValue'
Console.WriteLine(t.Get("InvalidProperty", "doesn't exist")); // Prints 'doesn't exist'
最佳答案
I want to know if there is a similar method/syntax when working with dynamic in .NET. I know that you can cast an ExpandoObject to a Dictionary, but sometimes there is no guarantee that a dynamic object is an Expando.
并且也不能保证它是编译时对象.
您可以使用try / catch,但这甚至没有说明该属性的存在.动态对象的一个例子:
public class MyDynamic: DynamicObject
{
static int Count = 0;
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = Count++;
if (binder.Name == "Test")
{
return Count % 2 == 0;
}
return false;
}
}
并假设你使用它
dynamic d = new MyDynamic();
try { Console.WriteLine(d.Test); } catch (Exception ex) { Console.WriteLine(ex.Message); }
try { Console.WriteLine(d.Test); } catch (Exception ex) { Console.WriteLine(ex.Message); }
try { Console.WriteLine(d.Test); } catch (Exception ex) { Console.WriteLine(ex.Message); }
try { Console.WriteLine(d.Test); } catch (Exception ex) { Console.WriteLine(ex.Message); }
对d.Test的一些调用将返回一个值,一些将抛出异常.所以我会说,没有安全的方法来测试它,并且没有任何默认值可能不存在的方法.