簡體   English   中英

反思返回類型以獲取字段及其文檔字符串?

[英]Reflection on return type to obtain fields and their docstrings?

我試圖確定返回類型所涉及的字段列表(在這種情況下,來自Ob類的“ string MyName”和“ string MyAddress”以及它們各自的文檔字符串)。

我進入了獲取返回類型的階段,但是我嘗試做的其他任何事情要么是給我空白值,要么是引發異常。 有什么建議么?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SampleProf
{
    class Program
    {

        static void Main(string[] args)
        {
            Sample cl = new Sample();
            Type myClType = cl.GetType();

            MethodInfo[] methodsInfo = myClType.GetMethods();

            List<string> MethodList = new List<string>();

            // Iterate through all methods
            foreach (MethodInfo methodInfo in methodsInfo)
            {
                if (methodInfo.IsPublic && methodInfo.Name.Contains("Get") && !methodInfo.Name.Contains("GetType"))
                {
                    if (methodInfo.ReturnType != typeof(void))
                    {
                        // Do something here?
                    }
                }
            }

            Console.Read();
        }

    }

    public class Sample
    {
        public Ob GetMe()
        {
            return null;
        }
    }

    public class Ob
    {
        /// <summary>My name</summary>
        string MyName;
        /// <summary>My address</summary>
        string MyAddress;
    }
}

這些是屬性還是字段?

對於屬性,這確實很容易,就像您已經檢索到方法一樣。

PropertyInfo[] pi = myClType.GetProperties();

對於字段,是這樣的(對於BindingFlags參數使用按位或):

myClType.GetFields(BindingFlags.Public | BindingFlags.NonPublic);

我認為您正在尋找的是methodInfo.ReturnType.GetFields()

一旦獲得了MethodInfo對象的數組,就可以繼續遍歷數組中的每個元素,查詢MethodInfo.ReturnType屬性以確定每個函數返回的類型。

獲得Type實例后,很容易反映其中包含的字段並分別打印其類型和名稱。

在適當的時候,我用適當的BindingFlags替換了您一些麻煩的條件檢查。 您不再需要檢查該方法是否為公共方法,也不需要檢查該方法是否為“ GetType”

static void Main(string[] args)
{
    Sample sampleInstance = new Sample();
    Type sampleType = sampleInstance.GetType();

    MethodInfo[] sampleMethods = 
        sampleType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

    foreach (MethodInfo method in sampleMethods)
    {
        var methodReturnType = method.ReturnType;

        if (methodReturnType == typeof(void)) 
            break;

        Console.WriteLine(methodReturnType.FullName);

        foreach (FieldInfo field in methodReturnType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
        {
            Console.WriteLine("  {0}: {1}",  field.DeclaringType, field.Name);       
        }
    }

    Console.Read();
}

暫無
暫無

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

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