C# 公共财产及其价值清单
.Net 4.5 C# 为了支持许多类的“导出到Excel”功能,我需要能够获取一个类,然后从中获取一个公共属性名称列表(用于标题)和属性值列表(用于行)C# 公共财产及其价值清单,c#,reflection,C#,Reflection,.Net 4.5 C# 为了支持许多类的“导出到Excel”功能,我需要能够获取一个类,然后从中获取一个公共属性名称列表(用于标题)和属性值列表(用于行) 是否有一种方法可以反映类的实例并获取属性名称和属性值?下面是一个快速示例,介绍如何执行此操作。当然,您需要对其进行更新,以便正确创建/构造CSV,但这会让您了解如何获得所需的值 class Program { static void Main(string[] args) { var myClass = new
是否有一种方法可以反映类的实例并获取属性名称和属性值?下面是一个快速示例,介绍如何执行此操作。当然,您需要对其进行更新,以便正确创建/构造CSV,但这会让您了解如何获得所需的值
class Program
{
static void Main(string[] args)
{
var myClass = new MyClass()
{
Number = 1,
String = "test"
};
var properties = myClass.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
var columnName = property.Name;
var value = myClass.GetType().GetProperty(columnName).GetValue(myClass, null);
Console.WriteLine(string.Format("{0} - {1}", columnName, value));
}
Console.ReadKey();
}
}
public class MyClass
{
public int Number { get; set; }
public string String { get; set; }
}
你可以用这样的方法:
public static Dictionary<string, object> KeyValue(object obj)
{
return obj.GetType().GetProperties().ToDictionary(
m => m.Name,
m => m.GetValue(obj, new object[] { })
);
}
publicstaticdictionary键值(objectobj)
{
返回obj.GetType().GetProperties().ToDictionary(
m=>m.Name,
m=>m.GetValue(obj,新对象[]{})
);
}
事实上,我最近为我的工作创造了类似的东西。我正在编写一个自定义CSV序列化程序类来支持一个构思不周的CSV文件规范
public CSVSerializer Serialize<T>(T data, Func<T, object> map)
{
if (map == null) throw new ArgumentNullException("map");
object mappedData = map(data);
if (mappedData == null) throw new NullReferenceException("Mapped data produced null value");
// Iterate over public members of `mappedData`
MemberInfo[] members = mappedData.GetType().GetMembers(BindingFlags.Instance | BindingFlags.Public);
List<string> values = new List<string>();
foreach (MemberInfo member in members)
{
// Skip events and methods
if (!(member is FieldInfo || member is PropertyInfo)) continue;
// Value of `mappedData`
object memberVal = MemberInfoValue(member, mappedData);
if (memberVal == null)
{
// If the actual value stored by `memberVal` is null, store string.Empty and continue
values.Add(string.Empty);
continue;
}
// Check if `memberVal` contains a member named "map"
MemberInfo[] maps = memberVal.GetType().GetMember("map");
MemberInfo memberMap = maps.Length > 0 ? maps[0] : null;
string val = MapToString(memberVal, o => o.ToString());
if (map != null) // map is present
{
// Get first property other than map
MemberInfo dataVal = memberVal.GetType().GetMembers(BindingFlags.Instance | BindingFlags.Public)
.Where(mi => mi is FieldInfo || mi is PropertyInfo)
.Except(new MemberInfo[] { memberMap })
.DefaultIfEmpty(memberMap)
.FirstOrDefault();
object tmp = MemberInfoValue(memberMap, memberVal);
if (dataVal == memberMap)
{
// map is only property, so serialize it
val = MapToString(tmp, o => o.ToString());
}
else
{
// try to serialize map(dataVal), or use empty string if it fails
Delegate dlg = tmp as Delegate;
if (dlg != null)
{
object param = MemberInfoValue(dataVal, memberVal);
try { val = MapToString(dlg, d => d.DynamicInvoke(param).ToString()); }
catch (Exception ex)
{
// exception should only occur with parameter count/type mismatch
throw new SerializationException(string.Format("Poorly formatted map function in {0}", member.Name), ex);
}
}
else
{
// map is not a delegate (!!)
throw new SerializationException(string.Format("map member in {0} is not a delegate type", member.Name));
}
}
}
// Handle quotes and the separator string
val = val.Trim('"');
if (val.Contains("\""))
{
val = val.Replace("\"", "\\\"");
}
if (val.Contains(Separator))
{
val = string.Format("\"{0}\"", val);
}
values.Add(val);
}
string line = string.Join(Separator, values);
Writer.WriteLine(line);
return this;
}
我有一个重载Serialize
,它调用Serialize(数据,d=>d)代码>。搜索“地图”成员可以执行以下操作:
mySerializer.Serialize(new {
employeeID = new { val = myEmployeeObject.ID, map = d => d.ToUpperCase() },
employeeName = myEmployeeObject.Name
});
mySerializer.Serialize(new {
employeeID = new { val = myEmployeeObject.ID, map = d => d.ToUpperCase() },
employeeName = myEmployeeObject.Name
});