我有一个自定义属性:
public class InterfaceForPartialModelAttribute : Attribute
{
//...
}
该属性应用于接口(不在属性上)。
namespace DAL.Model
{
[InterfaceForPartialModelAttribute] //<--custom attribute
public interface IActivity_part
{
string ActivityName { get; set; }
ActivityTypeEnum ActivityType { get; set; }
bool IsActivityDetailsCompleted { get; set; }
}
}
使用反射,我想扫描装配并检查具有我的自定义属性的所有接口:
Assembly[] assemblyArray = AppDomain.CurrentDomain.GetAssemblies();
var assTypes = assemblyArray[8].GetTypes(); //the 9th assembly is the one I've applied the attribute... this is irrelevant
string ns = "DAL.Model";
for (int i = 0; i < assTypes.Length; i++)
{
bool hasDataContractAttribute = assTypes[i].GetCustomAttributes(typeof(InterfaceForPartialModelAttribute), true).Any();
if (assTypes[i].IsInterface && assTypes[i].Namespace == ns && hasDataContractAttribute == true)
{
if (assTypes[i].Name == "IActivity_part")
{
Console.WriteLine("type found!");
}
Console.WriteLine("zr type: " + assTypes[i].Name);
Console.WriteLine("zr ns : " + assTypes[i].Namespace);
Console.WriteLine("---------------------------------------------");
}
}
控制台不会显示任何结果, hasDataContractAttribute永远不会为真,怎么办? 似乎 GetCustomAttributes 返回应用于属性的属性。但我正在寻找应用于接口级别的属性。大多数在线示例展示了如何通过对属性的反思来获取自定义属性。