[英]C# and Reflection
我是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#几天,却无法弄清楚。
任何建议,想法和/或代码示例将不胜感激!
这与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.
}
}
您可以通过以下方式调用它:
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`.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.