我有这种通用方法:
public Guid Save<T>(T obj)
{
Guid newId = Guid.NewGuid();
try
{
foreach (MethodInfo method in (typeof(T)).GetMethods())
{
if (IsXmlElement(method))
{
// A way to get this method's value
// e.g. if T has method GetName, and GetName was assigned 'John'
//i.e. object.GetName = 'John'Is there a way to get 'John' from this GetName method?
}
}
然后,我有一个对象,myObject.Name = 'John'
...并将myObject传递给save方法,因此:Save(myObject);
有什么方法可以在Save方法中获取值“ John”?
任何建议,将不胜感激。谢谢。
如果要基于泛型类型遍历属性(假设您在示例中说“方法”时指的是属性),则可以使用TypeDescriptor
该类:
public Guid Save<T>(T obj)
{
Guid newId = Guid.NewGuid();
try
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(typeof(T)))
{
if (IsXmlElement(method))
{
object value = property.GetValue(obj);
// ...
}
}
如果您总是推断类型(即总是推断T
类型,obj
而不是基本类型或接口),则根本不需要泛型:
public Guid Save(object obj)
{
Guid newId = Guid.NewGuid();
try
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(obj))
{
if (IsXmlElement(method))
{
object value = property.GetValue(obj);
// ...
}
}
您可能还想签出XmlSerializer
课程。看来您是在手动从源对象创建XML。XmlSerializer
可能已经用较少的工作便拥有了您所需的一切。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句