【发布时间】: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