gpt4 book ai didi

c# - 在 MetadataProvider 中获取多个相同类型的属性

转载 作者:行者123 更新时间:2023-12-05 05:23:39 24 4
gpt4 key购买 nike

我有一个属性,它有 AllowMultiple:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class AllowedDeviceTypesAttribute : System.Attribute
{
//...
}

我在我的属性(property)上多次使用它:

[AllowedDeviceTypes(DeviceTypes.StaticRegister)]
[AllowedDeviceTypes(DeviceTypes.MobileRegister)]
public int ClientNr { get; set; }

我有一个自定义模型元数据提供程序:

public class ExtendedModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<System.Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var attributeList = attributes as IList<System.Attribute> ?? attributes.ToList();
var data = base.CreateMetadata(attributeList, containerType, modelAccessor, modelType, propertyName);
//...
var allowedDeviceTypesAttributes = attributeList.Where(a => typeof(AllowedDeviceTypesAttribute) == a.GetType()).ToList();
if (allowedDeviceTypesAttributes.Count > 0)
{
var allowedDeviceTypes = allowedDeviceTypesAttributes.Cast<AllowedDeviceTypesAttribute>().Select(e => e.AllowedDeviceType).ToList();
data.AdditionalValues.Add(AllowedDeviceTypesAttribute.AdditionalMetaDataValue, allowedDeviceTypes);
}

return data;
}
}

我的问题是,我在 attributes 中总是只有一个 AllowedDeviceTypesAttribute:

enter image description here

如何获得这两个属性?

[AllowedDeviceTypes(DeviceTypes.StaticRegister)]
[AllowedDeviceTypes(DeviceTypes.MobileRegister)]

最佳答案

为了让它工作,我们需要覆盖 TypeId 属性:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class AllowedDeviceTypesAttribute : System.Attribute
{
//...
public override object TypeId
{
get
{
return this;
}
}
}

关于c# - 在 MetadataProvider 中获取多个相同类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37104614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com