【问题标题】:C# and ReflectionC# 和反射
【发布时间】:2009-08-30 02:30:42
【问题描述】:

我是 C# 的新手,虽然不是编程,所以如果我把事情搞混了,请原谅我——这完全是无意的。我编写了一个相当简单的类,称为“API”,它有几个公共属性(访问器/突变器)。我还编写了一个测试控制台应用程序,它使用反射来获取按字母顺序排列的类中每个属性的名称和类型列表:

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

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

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

【问题讨论】:

    标签: c# .net oop reflection


    【解决方案1】:

    这与static 构造函数无关。您可以使用static methods

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

    你可以这样称呼它:

    API.PrintAPI(); 
    

    在调用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`.
        } 
    }
    

    【讨论】:

    • 这正是我所需要的——非常感谢!还有一个问题:我遇到了以前的 Stackoverflow 问题,它提出了以下建议:“..当您反思以查找支持某个属性的所有类型时,您有一个使用缓存的绝佳机会。这意味着您没有在运行时多次使用反射。”这似乎描述了我想要做的事情,但我不知道我需要进行哪些更改(以及在哪里)才能仅在加载时执行此操作。有什么建议吗?
    • AspNyc,要创建缓存,您只需将 Mehrdad 描述的 PrintApi 方法的结果存储到一个集合中,例如 ArrayList 或通用版本 List。存储或持久化集合或缓存的位置取决于您。它可能在您查询的对象或启动查询的客户端代码中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多