【发布时间】:2021-11-01 11:55:40
【问题描述】:
我有一个类 DocumentObject,它扩展 DynamicObject 以允许动态成员属性。
public class DocumentObject : DynamicObject
{
/// <summary>
/// Inner dictionary that holds the dynamic members of the object
/// </summary>
Dictionary<string, object> dictionary = new Dictionary<string, object>();
/// <summary>
/// Try to get the member that is not defined in the class (additional dynamic members) from inner dictionary
/// </summary>
/// <param name="binder"></param>
/// <param name="result"></param>
/// <returns></returns>
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
// Converting the property name to lowercase
// so that property names become case-insensitive.
string name = binder.Name.ToLower();
// If the property name is found in a dictionary,
// set the result parameter to the property value and return true.
// Otherwise, return false.
return dictionary.TryGetValue(name, out result);
}
/// <summary>
/// Try to set the member that is not defined in the class (additional dynamic members) to inner dictionary
/// </summary>
/// <param name="binder"></param>
/// <param name="value"></param>
/// <returns></returns>
public override bool TrySetMember(SetMemberBinder binder, object value)
{
// Converting the property name to lowercase
// so that property names become case-insensitive.
dictionary[binder.Name.ToLower()] = value;
// You can always add a value to a dictionary,
// so this method always returns true.
return true;
}
/// <summary>
/// Get the names of all the dynamic members
/// </summary>
/// <returns></returns>
public override IEnumerable<string> GetDynamicMemberNames()
{
return dictionary.Keys;
}
}
我有一个继承 DocumentObject 的基本 Person 类
public class PersonDto : DocumentObject
{
[JsonProperty("id")]
public string Id { get; set; }
}
另一个继承 PersonDto 的子 OfficePersonDto 类
public class OfficePersonDto : PersonDto
{
[JsonProperty("name")]
public string Name { get; set; }
}
在我的函数中,我收到的 JSON 对象必须至少是 PersonDto 对象,但如果它是 OfficePersonDto 类型,我希望能够将 PersonDto 转换为 OfficePersonDto。
IE。 JSON = {"Id":1, "Name": "Orchard"},在 PersonDto 中,name 属性将使用 DocumentObject 的字典保存,而在转换为 OfficePersonDto 时,Id 和 name 都是该类的属性。
如何从 PersonDto 转换为子类,例如OfficePersonDto?
PersonDto personDto = ...
OfficePersonDto off = personDto as OfficePersonDto // results in null or Name is null
【问题讨论】:
标签: c# dynamicobject