Mil*_*lee 3 c# properties invoke custom-attributes c#-4.0
[AttributeUsage(AttributeTargets.Method,AllowMultiple=true)]
public class MethodId : Attribute
{
private int mId;
public MethodId(int mId)
{
this.mId = mId;
}
public int methodId
{
get { return this.mId; }
set { this.mId = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
public class Methods
{
[MethodId(1)]
public void square()
{ }
[MethodId(2)]
public void Notify()
{ }
}
Run Code Online (Sandbox Code Playgroud)
如何在MethodId的帮助下访问main()或任何其他类中的square()?
private static MethodInfo GetMethodInfo(int id)
{
return typeof(Methods).GetMethods().
Where(x => x.GetCustomAttributes(false).OfType<MethodId>().Count() > 0)
.Where(x => x.GetCustomAttributes(false).OfType<MethodId>().First().methodId == id)
.First();
}
Run Code Online (Sandbox Code Playgroud)
用法:
var methodInfo = GetMethodInfo(1);
methodInfo.Invoke(new Methods(), null);
Run Code Online (Sandbox Code Playgroud)
此解决方案仅用于显示如何执行此操作.没有优化表现.理想情况下,您将缓存 methodInfos.
归档时间: |
|
查看次数: |
5878 次 |
最近记录: |