2014-09-06 105 views

回答

0

我不確定,如果我錯誤地理解了你的問題。但是你是否在談論下面那種裝飾方法的屬性。我在探索屬性時創建了這些代碼。我在這裏粘貼它。希望能幫助到你。

在此,我創建了屬性[Allow(「Valid」)],如果它有效,我們可以調用該方法,否則不會。

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(); 

    } 
    } 
} 
+0

非常感謝您的寶貴意見Ganesh – Elamparthi 2014-09-06 17:25:40

+0

歡迎您。如果回答有幫助,請投票,這對社區更好。 – Ganesh 2014-09-07 05:28:53

+0

Ganesh可以告訴我xml屬性中的同樣的東西...只需xml屬性讀取該方法。如果該方法與給定字符串相比時爲真,則它允許該方法,否則不會。 – Elamparthi 2014-09-07 07:28:59

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; 
} 
+0

謝謝Hamix – Elamparthi 2014-09-06 11:05:58

+0

喜的朋友, 我需要在C#中做自定義屬性的幫助。 我有3個字符串變量...名稱爲A,B,C。 [自定義屬性,如果(A = true)] //它在調用方法時進入方法。 [自定義屬性,如果(B = false)] //它終止 [自定義屬性,如果(C = true)] //與A相同則向方法中輸入int。 public _somemethod() { //部分代碼 } – Elamparthi 2014-09-08 05:17:28