從羅斯林分析儀
除此之外,PostSharp是一個可能的路要走。
下面是一個基本實現這樣的檢查和錯誤輸出:
[MulticastAttributeUsage(PersistMetaData = true)]
public class TlvContractAttribute : TypeLevelAspect
{
public override void CompileTimeInitialize(Type target, AspectInfo aspectInfo)
{
Dictionary<int, PropertyInfo> indexes = new Dictionary<int, PropertyInfo>();
foreach (PropertyInfo propertyInfo in target.GetProperties())
{
TlvMemberAttribute memberAttr =
propertyInfo.GetCustomAttributes()
.Where(x => x is TlvMemberAttribute)
.Cast<TlvMemberAttribute>()
.SingleOrDefault();
if (memberAttr == null)
{
Message.Write(MessageLocation.Of(propertyInfo), SeverityType.Error, "USR001",
"Property {0} should be marked by TlvMemberAttribute.", propertyInfo);
continue;
}
if (indexes.ContainsKey(memberAttr.Index))
{
Message.Write(MessageLocation.Of(propertyInfo), SeverityType.Error, "USR002",
"Property {0} marked by TlvMemberAttribute uses Index {1}, which is already used by property {2}.",
propertyInfo, memberAttr.Index, indexes[memberAttr.Index]);
continue;
}
indexes[memberAttr.Index] = propertyInfo;
}
}
}
它可以在你定義它的程序集。您只需確保PostSharp實際上在您希望檢查工作的所有程序集上運行。
如果您的屬性需要不同的基類,則還可以實現ITypeLevelAspect
和ITypeLevelAspectBuildSemantics
接口。
很好的回答!謝謝!!! – Franki1986