从未知对象获取属性和值

m4r*_*4rc 137 c# reflection

从PHP的世界,我决定给C#一个去.我有一个搜索,但似乎无法找到如何做到相当于这个的答案.

$object = new Object();

$vars = get_class_vars(get_class($object));

foreach($vars as $var)
{
    doSomething($object->$var);
}
Run Code Online (Sandbox Code Playgroud)

我基本上有一个对象列表.该对象可以是三种不同类型之一,并且具有一组公共属性.我希望能够获得对象的属性列表,循环它们然后将它们写入文件.我认为这与c#反射有关,但这对我来说都是新的.

任何帮助将不胜感激.

Coc*_*lla 261

这应该这样做:

Type myType = myObject.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

foreach (PropertyInfo prop in props)
{
    object propValue = prop.GetValue(myObject, null);

    // Do something with propValue
}
Run Code Online (Sandbox Code Playgroud)

  • 没有必要从数组创建一个列表,只需`PropertyInfo [] props = input.GetType().GetProperties();` (19认同)
  • @jonathan`System.Reflection`命名空间 (8认同)
  • 您想使用`Newtonsoft.Json.JsonConvert`更新2017年答案吗? (2认同)
  • @clone 这是一种完全不同的方式。如果您认为这是一种有效的方法,则应该发布答案 (2认同)
  • @Jonesopolis 如何从“dynamic”获取属性,而不先将其转换为“object”,然后执行与我的答案相同的操作? (2认同)

cas*_*One 17

是的,反思将是要走的路.首先,您将获得Type表示列表中实例的类型(在运行时).您可以通过调用GetType方法Object来执行此操作.因为它在Object类中,所以它可以被.NET中的每个对象调用,因为所有类型都派生自Object(从技术上讲,并非一切,但这在这里并不重要).

获得Type实例后,可以调用该GetProperties方法来获取PropertyInfo表示运行时信息的实例,以获取有关该属性的属性Type.

请注意,您可以使用的重载GetProperties,以帮助进行分类哪些您检索性能.

从那里,您只需将信息写入文件.

您上面翻译的代码将是:

// The instance, it can be of any type.
object o = <some object>;

// Get the type.
Type type = o.GetType();

// Get all public instance properties.
// Use the override if you want to classify
// which properties to return.
foreach (PropertyInfo info in type.GetProperties())
{
    // Do something with the property info.
    DoSomething(info);
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果您需要方法信息或字段信息,则必须分别调用GetMethodsGetFields方法的重载之一.

另请注意,将成员列出到文件是一回事,但是不应该使用此信息来基于属性集来驱动逻辑.

假设您可以控制类型的实现,您应该从公共基类派生或实现公共接口并对其进行调用(您可以使用asis运算符来帮助确定您正在使用哪个基类/接口)运行).

但是,如果您不控制这些类型定义并且必须基于模式匹配来驱动逻辑,那么这很好.


小智 16

void Test(){
    var obj = new{a="aaa", b="bbb"};

    var val_a = obj.GetValObjDy("a"); //="aaa"
    var val_b = obj.GetValObjDy("b"); //="bbb"
}
//create in a static class
static public object GetValObjDy(this object obj, string propertyName)
{            
     return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*rMP 10

好吧,在C#中它是相似的.这是最简单的例子之一(仅适用于公共属性):

var someObject = new { .../*properties*/... };
var propertyInfos = someObject.GetType().GetProperties();
foreach (PropertyInfo pInfo in PropertyInfos)
{
    string propertyName = pInfo.Name; //gets the name of the property
    doSomething(pInfo.GetValue(someObject,null));
}
Run Code Online (Sandbox Code Playgroud)


RAJ*_*RAJ 9

从属性名称获取特定属性值

public class Bike{
public string Name {get;set;}
}

Bike b = new Bike {Name = "MyBike"};
Run Code Online (Sandbox Code Playgroud)

从字符串名称属性访问Name的属性值

public object GetPropertyValue(string propertyName)
{
//returns value of property Name
return this.GetType().GetProperty(propertyName).GetValue(this, null);
} 
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用GetType - GetProperties - Linq Foreach

obj.GetType().GetProperties().ToList().ForEach(p =>{
                                                        //p is each PropertyInfo
                                                        DoSomething(p);
                                                    });
Run Code Online (Sandbox Code Playgroud)


小智 5

使用 Linq 的单行解决方案...

var obj = new {Property1: 1, Property2: 2};
var property1 = obj.GetType().GetProperties().First(o => o.Name == "Property1").GetValue(obj , null);
Run Code Online (Sandbox Code Playgroud)