![](/img/trans.png)
[英]Dynamic object doesn't contain a definition for a property from a reference
[英]Get a default value if dynamic object doesn't contain property
使用多種語言的動態對象時,有一個構造允許您獲取屬性的值,如果該屬性不存在,則返回默認值。
我想知道在.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'
我想知道在.NET中使用dynamic時是否有類似的方法/語法。 我知道您可以將ExpandoObject強制轉換為Dictionary,但有時無法保證動態對象是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
一些調用將返回一個值,一些將拋出異常。 所以我會說,沒有安全的方法來測試它,並且沒有任何默認值可能不存在的方法。
如果你在談論ExpandoObjects,它們只是字典。 這意味着您可以將它們轉換為IDictionary,並查看該鍵是否與您的屬性名稱匹配。 這可以在通用擴展方法中完成。
public static T PropertyOrDefault<T>(this ExpandoObject obj, string propertyName)
{
var dynamicAsDictionary = (IDictionary<string, object>)obj;
if (!dynamicAsDictionary.ContainsKey(propertyName))
{
return default(T);
}
object propertyValue = dynamicAsDictionary[propertyName];
if (!(propertyValue is T))
{
return default(T);
}
return (T)propertyValue;
}
如果動態不是ExpandoObject,那么您需要使用反射。
public static T PropertyOrDefault<T>(dynamic obj, string propertyName)
{
if (obj is ExpandoObject)
{
return ((ExpandoObject)obj).PropertyOrDefault<T>(propertyName);
}
Type objectType = obj.GetType();
PropertyInfo p = objectType.GetProperty(propertyName);
if (p != null)
{
object propertyValue = p.GetValue(obj);
if (propertyValue is T)
{
return (T)propertyValue;
}
}
return default(T);
}
如果我將注釋中的答案轉換為非擴展方法,則以下方法有效:
public bool HasProperty(Object o, string propertyName)
{
return o.GetType().GetProperty(propertyName) != null;
}
...
dynamic t = new
{
validProperty = "value",
};
MessageBox.Show(HasProperty(t, "invalidProperty")?"true":"false");
MessageBox.Show(HasProperty(t, "validProperty") ?"true":"false");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.