C# 每个类的唯一属性值
这是我的属性类:C# 每个类的唯一属性值,c#,attributes,C#,Attributes,这是我的属性类: [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class TagAttribute : Attribute { public TagAttribute (string tag) { Tag = tag; } public string Tag { get; set; } } 其思想是创建一个
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class TagAttribute : Attribute
{
public TagAttribute (string tag)
{
Tag = tag;
}
public string Tag { get; set; }
}
其思想是创建一个类,并使用标记属性和标记值装饰每个属性。例如:属性名将具有属性标记(“UserId”)
我需要检查的验证之一是每个类属性的标记值(“UserId”)是唯一的。这意味着没有其他属性具有相同值(“UserId”)的标记
我很确定有一个简单的方法可以让LINQ做到这一点,但是演员的选择也必须完成,我非常感谢你的帮助:)
提前感谢:)此代码将打印给定程序集中的所有重复标记,以及具有此标记的属性列表:
Assembly asm = ...
var propertiesByTag =
from t in asm.GetTypes()
from p in t.GetProperties()
from a in p.GetCustomAttributes(typeof(TagAttribute)).Cast<TagAttribute>()
group p by a.Tag into g
select new
{
Tag = g.Key,
Properties = g.ToArray()
}
foreach (var dup in propertiesByTag.Where(x => x.Properties.Length > 1))
{
Console.WriteLine("Duplicated tag: {0}", dup.Tag);
foreach(var p in dup.Properties)
Console.WriteLine("\t{0}.{1}", p.DeclaringType.Name, p.Name);
}
Assembly asm=。。。
var propertiesByTag=
来自asm.GetTypes()中的t
来自t.GetProperties()中的p
从p.GetCustomAttributes(typeof(TagAttribute)).Cast()中的
按a分组p。标记为g
选择新的
{
标记=g.键,
属性=g.ToArray()
}
foreach(propertiesByTag.Where(x=>x.Properties.Length>1)中的var dup)
{
WriteLine(“重复标记:{0}”,dup.tag);
foreach(重复属性中的var p)
Console.WriteLine(“\t{0}.{1}”,p.DeclaringType.Name,p.Name);
}