C#和反思

Mas*_*Net 2 .net c# oop reflection

我是C#的全新手,虽然没有编程,所以如果我混淆了一点,请原谅我 - 这完全是无意的.我编写了一个名为"API"的相当简单的类,它有几个公共属性(访问器/ mutator).我还编写了一个测试控制台应用程序,它使用反射来获取类中每个属性的名称和类型的字母顺序列表:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using MyNamespace;      // Contains the API class

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hi");

            API api = new API(1234567890, "ABCDEFGHI");
            Type type = api.GetType();
            PropertyInfo[] props = type.GetProperties(BindingFlags.Public);

            // Sort properties alphabetically by name.
            Array.Sort(props, delegate(PropertyInfo p1, PropertyInfo p2) { 
                return p1.Name.CompareTo(p2.Name); 
            });

            // Display a list of property names and types.
            foreach (PropertyInfo propertyInfo in type.GetProperties())
            {
                Console.WriteLine("{0} [type = {1}]", propertyInfo.Name, propertyInfo.PropertyType);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我需要的是一个循环遍历属性并将所有值连接成一个查询字符串的方法.问题是我想让它成为API类本身的一个功能(如果可能的话).我想知道静态构造函数是否与解决这个问题有关,但我只使用了C#几天,并且无法弄明白.

任何建议,想法和/或代码示例将不胜感激!

Meh*_*ari 5

这与static构造函数无关.你可以用static方法做到:

class API {
    public static void PrintAPI() {
       Type type = typeof(API); // You don't need to create any instances.
       // rest of the code goes here.
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以用以下方式调用它:

API.PrintAPI(); 
Run Code Online (Sandbox Code Playgroud)

调用static方法时不使用任何实例.

更新:要缓存结果,您可以在第一次调用或static初始化程序中执行此操作:

class API {
    private static List<string> apiCache;
    static API() {
        // fill `apiCache` with reflection stuff.
    }

    public static void PrintAPI() {
        // just print stuff from `apiCache`.
    } 
}
Run Code Online (Sandbox Code Playgroud)