簡體   English   中英

從委托獲取基礎類的類型

[英]Get type of underlying class from a delegate

我有一些類繼承了相同的接口IParsee 它們都具有[Regex]屬性。 我需要制作一個Parser類,向其傳遞一個字符串和一個代表數組以解析給定的字符串並返回一個IParsee對象數組。 問題是我想保持代碼干燥,而不是在每個IParsee類中編寫用於匹配字符串的方法,但我想在Parser類中編寫它。 我不知道如何通過其方法獲取類的類型。 我看到可以在方法上調用GetType() ,但是如果給出了錯誤的字符串來解析,則我的方法將引發錯誤。

Parser方法:

public class Parser
{
    public static List<IParsee> Parse(String text, params Func<String, IParsee>[] meth)
{
        List<IParsee> list = new List<IParsee>();
        IParsee res;
        for (int i = 0; i < meth.Length; i++)    
            // here i want to get the regex attribute and the MatchCollection
            // looping through the MatchCollection parsing 
            // every match and pushing it to the list

        return list;
}

我需要解析的類中的方法:

[RegexAttribute(@"\w+\s\w+\swas\sborn\son\s(\d{4}/\d\d/\d\d)"]
public class Person : IParsee
{
   public static IParsee Parse(string str)
   {

所以我稱之為

List<IParsee> l = Parser.Parse(person.ToString(), Person.Parse);

您可以使用所傳遞方法的聲明類型:

for (int i = 0; i < meth.Length; i++)
{
    RegexAttribute attribute = meth[i].GetMethodInfo().DeclaringType
                                .GetCustomAttribute<RegexAttribute>();

    // assume you have a property called YourStringProperty in RegexAttribute
    string regexAttributeValue = attribute.YourStringProperty;
}

DeclaringType表示在其上定義方法的類(類型)。

GetCustomAttribute用於獲取在方法或類上標記的屬性。

每個委托都有一個Method屬性,使您可以訪問MethodInfo實例,該實例保存有關委托引用的方法的所有元數據。 要訪問此屬性,必須將Func<T,TResult>轉換為Delegate 然后從MethodInfo可以輕松獲取DeclaringType

Type methodClass = ((Delegate)meth[i]).Method.DeclaringType

現在,您可以從methodClass檢索屬性:

RegexAttribute attr = (RegexAttribute)methodClass.GetCustomAttribute(typeof(RegexAttribute));

注意:如果Parse方法不是靜態的,則可以使用Delegate.Target來訪問實際實例。 因此,必須在后代類上聲明[Regex]屬性,並且該屬性仍將起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM