刚学习c# 再看反射,写了反射的demo
遇到了点小问题。不知道哪里不对。就是找不到对应的属性!
代码如下:
using System;
using System.Reflection;
namespace DemoClass
{
[LastModified("2015/1/24","MyTest")]
public class DemoClass
{
static void Main(string[] args)
{
Type clsType = typeof(DemoClass);
Assembly assy = clsType.Assembly;
String assyName = assy.GetName().Name;
bool isdef = Attribute.IsDefined(assy,
typeof(LastModifiedAttribute));
if (isdef)
{
// Affirm that the attribute is defined.
Console.WriteLine("The AssemblyDescription attribute " +
"is defined for assembly {0}.", assyName);
// Get the description attribute itself.
LastModifiedAttribute adAttr =
(LastModifiedAttribute)Attribute.GetCustomAttribute(
assy, typeof(LastModifiedAttribute));
// Display the description.
if (adAttr != null)
Console.WriteLine("The DateModified is \"{0}\".",
adAttr.DateModified);
else
Console.WriteLine("The DateModified could not " +
"be retrieved.");
}
else
Console.WriteLine("The LastModifiedAttribute attribute is not " +
"defined for assembly {0}.", assyName);
Console.ReadKey();
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
public class LastModifiedAttribute : Attribute
{
private readonly DateTime dateModified;
public DateTime DateModified { get { return dateModified; } }
private readonly string changes;
public string Changes { get { return changes; } }
public string Issues { get; set; }
public LastModifiedAttribute(string dateModified, string changes)
{
this.dateModified = DateTime.Parse(dateModified);
this.changes = changes;
}
}
}
------解决思路----------------------
你这是把attribute定义在class上,但是从assembly上取它,所以找不到。
或者从class上取,或者是把attribute定义在assembly上才对。
------解决思路----------------------
IsDefined 有许多个版本, 楼主用错了, 应该如下:
bool isdef = Attribute.IsDefined(clsType, typeof(LastModifiedAttribute));