通过自定义属性传递值以进行方法访问

时间:2014-09-06 09:45:32

标签: c#

任何人都可以告诉我方法的自定义属性。我需要将一个字符串传递给attribute.If字符串为true然后我将访问该方法,否则不访问该方法。

2 个答案:

答案 0 :(得分:1)

我不确定,如果我错误地理解你的问题。但是你在谈论以下类型的装饰方法的属性。我在探索属性时创建了这段代码。我在这里粘贴它。希望它有所帮助。

在这里,我创建了属性,[允许("有效")]如果它有效,我们可以调用该方法,否则不会。

namespace ConsoleApplication1
{

  using System;
[AttributeUsage(AttributeTargets.All)]
public class AllowAttribute : System.Attribute 
{
   public readonly string SomeString;

   public AllowAttribute(string someString)  // your string is passed in custom attribute 
   {
      this.SomeString = someString;
   }


}
public interface IAllowAttributeInvoker
{
  object AllowAttributeInvokeMethod<T>(string methodName, T classInstance, object[] parametersArray);

}

public  class AllowAttributeInvoker: IAllowAttributeInvoker
{
  public object AllowAttributeInvokeMethod<T>(string methodName, T classInstance, object[] parametersArray)
  {
    System.Reflection.MemberInfo info = typeof(T).GetMethod(methodName);
    if (IsAttributeValid(info))
    {
      var method = (typeof (T)).GetMethod(methodName);
      Console.WriteLine("Invoking method");
      var result = method.Invoke(classInstance, parametersArray);

      return result;
    }
    else
    {
      Console.WriteLine("Can not invoke this method.");
    }
    return null;
  }


  private static bool IsAttributeValid(MemberInfo member)
   {
        foreach (object attribute in member.GetCustomAttributes(true))
        {
            if (attribute is AllowAttribute && ((AllowAttribute)attribute).SomeString == "Valid")
            {
               return true;
            }
        }
      return false;
   }
}


  public class EmployeeService :AllowAttributeInvoker
  {

    public object PaySalary()
    {
      return AllowAttributeInvokeMethod("PaySalaryInvoke", this, null);
    }

    [Allow("Valid")]
    public void PaySalaryInvoke()
    {

      Console.WriteLine("Salary Paid.");
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      Console.ReadLine();

      EmployeeService service = new EmployeeService();
      service.PaySalary();
      Console.ReadLine();

    }
  }
}

答案 1 :(得分:0)

1 - 您可以定义公共用户访问列表:

public List<string> AccessRules = new List<string>();

2 - 在构造函数中设置用户访问规则:

AccessRules.AddRange(new[] { "GetCurrentDateTime", "GetCurrentDate" });

3 - 在安全方法中检查用户访问规则

public DateTime GetCurrentDateTime()
{
   bool haveAccess = AccessRules.Any(c => c == "GetCurrentDateTime");
   if (haveAccess)
   {
      return DateTime.Now;
   }
   return null;
}