OhS*_*nap 1 c# linq reflection
我正在寻找一种在单个LINQ语句中选择具有特定自定义属性和特定值的属性的方法。
我得到了具有所需属性的属性,但是不知道如何选择其特定值。
<AttributeUsage(AttributeTargets.Property)>
Public Class PropertyIsMailHeaderParamAttribute
Inherits System.Attribute
Public Property HeaderAttribute As String = Nothing
Public Property Type As ParamType = Nothing
Public Sub New()
End Sub
Public Sub New(ByVal headerAttribute As String, ByVal type As ParamType)
Me.HeaderAttribute = headerAttribute
Me.Type = type
End Sub
Public Enum ParamType
base = 1
open
closed
End Enum
End Class
private MsgData setBaseProperties(MimeMessage mailItem, string fileName)
{
var msgData = new MsgData();
Type type = msgData.GetType();
var props = from p in this.GetType().GetProperties()
let attr = p.GetCustomAttributes(typeof(Business.IT._21c.AddonFW.PropertyIsMailHeaderAttribute), true)
where attr.Length == 1
select new { Property = p, Attribute = attr.FirstOrDefault() as Business.IT._21c.AddonFW.PropertyIsMailHeaderAttribute };
}
Run Code Online (Sandbox Code Playgroud)
[解]
var baseProps = from p in this.GetType().GetProperties()
let attr = p.GetCustomAttribute<PropertyIsMailHeaderParamAttribute>()
where attr != null && attr.Type == PropertyIsMailHeaderParamAttribute.ParamType.@base
select new { Property = p, Attribute = attr as Business.IT._21c.AddonFW.PropertyIsMailHeaderParamAttribute };
Run Code Online (Sandbox Code Playgroud)
您必须将Attribute对象(使用常规转换或通过使用OfType<>扩展名)转换为您的类型,但是最简单的方法是使用的通用版本GetCustomAttribute<>:
var props = from p in this.GetType().GetProperties()
let attr = p.GetCustomAttribute<PropertyIsMailHeaderAttribute>()
where attr != null && attr.HeaderAttribute == "FooBar"
&& attr.Type = ParamType.open
select whatever;
Run Code Online (Sandbox Code Playgroud)