繁体   English   中英

C#获取通用对象内的对象

[英]C# Get object inside of object that is a generic

我有几个包含地址对象的视图模型。 该地址对象当然有address1,address2,city,state和zip。
我们正在使用邮政编码地址验证系统,我希望我的所有开发人员能够调用一个帮助程序类,它将为地址对象嗅探View Model对象。 如果找不到它,它将检查视图模型是否具有基本的address1,address2和etc属性......在任何一种情况下我都需要它来获取属性对象地址的地址信息或获取地址属性...

所以我的助手类方法签名如下所示:

 public void ShowVerificationWithReflection<T>(ModelStateDictionary modelState, T viewModel) where T : AMSBaseVM

然后我做以下事情:

var objType = viewModel.GetType();
List<PropertyInfo> properties = new List<PropertyInfo>();

properties.AddRange(objType.GetProperties());

foreach (PropertyInfo property in properties)
{
    if (property.CanRead)
    {
        if (property.Name == "Address1") testAddress.Address1 = property.GetValue(viewModel, null) as string;
        if (property.Name == "Address2") testAddress.Address2 = property.GetValue(viewModel, null) as string;
        if (property.Name == "City") testAddress.City = property.GetValue(viewModel, null) as string;
        if (property.Name == "StCd") testAddress.StateCodeId = (long)property.GetValue(viewModel, null);
        if (property.Name == "Zip") testAddress.Zip = property.GetValue(viewModel, null) as string;
    }
}

这适用于View Model的一部分地址属性。 现在我磕磕绊绊的是检测View Model是否有这样的属性:

 public EntityAddressVM Address { get; set; }

我需要从泛型中获取该对象,然后获取其地址属性。 我已经找到了这个对象,但之后我就被卡住了......

 bool hasEntityAddress = objType.GetProperties().Any(p => p.PropertyType == typeof(EntityAddressVM));

我需要帮助的是:

  1. 确定传入的viewModel(mvc)是否具有地址对象或具有地址属性。

  2. 如果它确实有地址对象,则获取地址属性,否则从ViewModel获取地址属性。

我用一个很好的扩展方法来查看对象属性:

/// <summary>
///     Gets all public properties of an object and and puts them into dictionary.
/// </summary>
public static IDictionary<string, object> ToDictionary(this object instance)
{
    if (instance == null)
        throw new NullReferenceException();

    // if an object is dynamic it will convert to IDictionary<string, object>
    var result = instance as IDictionary<string, object>;
    if (result != null)
        return result;

    return instance.GetType()
        .GetProperties()
        .ToDictionary(x => x.Name, x => x.GetValue(instance));
}

然后你可以做这样的事情:

var addressObject = model
    .ToDictionary()
    .FirstOrDefault(x => x.Value is EntityAddressVM)
    .Value;

如果为null则从模型中获取Address属性。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM