Assume that I have a dynamic variable:
假设我有一个动态变量:
dynamic d = *something*
Now, something creates properties to d
which I have on the other hand from a string array:
现在,我从一个字符串数组中,从另一个角度来创建属性d
string[] strarray = { 'property1','property2',..... }
I don't know the property names in advance.
我不提前知道物业的名称。
How in code, once d
is created and strarray is pulled from DB, can I get the values?
在代码中,一旦创建了d,从DB中提取了strarray,我能得到值吗?
I want to get d.property1 , d.property2
.
我想要d。property1 d.property2。
I see that the object has a _dictionary
internal dictionary that contains the keys and the values, how do I retrieve them?
我看到对象有一个包含键和值的_dictionary内部字典,如何检索它们?
8 个解决方案
#1
81
I don't know if there's a more elegant way with dynamically created objects, but using plain old reflection should work:
我不知道动态创建对象是否有更优雅的方式,但是使用普通的旧反射应该工作:
var nameOfProperty = "property1";
var propertyInfo = myObject.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);
GetProperty
will return null
if the type of myObject
does not contain a public property with this name.
如果myObject类型不包含具有此名称的公共属性,则GetProperty将返回null。
EDIT: If the object is not a "regular" object but something implementing IDynamicMetaObjectProvider
, this approach will not work. Please have a look at this question instead:
编辑:如果对象不是“常规”对象,而是实现IDynamicMetaObjectProvider的东西,则此方法将不起作用。请看看这个问题:
- How do I reflect over the members of dynamic object?
- 如何反映动态对象的成员?
#2
18
This will give you all property names and values defined in your dynamic variable.
这将给您提供在动态变量中定义的所有属性名和值。
dynamic d = { // your code };
object o = d;
string[] propertyNames = o.GetType().GetProperties().Select(p => p.Name).ToArray();
foreach (var prop in propertyNames)
{
object propValue = o.GetType().GetProperty(prop).GetValue(o, null);
}
#3
18
Hope this would help you:
希望这对你有帮助:
public static object GetProperty(object o, string member)
{
if(o == null) throw new ArgumentNullException("o");
if(member == null) throw new ArgumentNullException("member");
Type scope = o.GetType();
IDynamicMetaObjectProvider provider = o as IDynamicMetaObjectProvider;
if(provider != null)
{
ParameterExpression param = Expression.Parameter(typeof(object));
DynamicMetaObject mobj = provider.GetMetaObject(param);
GetMemberBinder binder = (GetMemberBinder)Microsoft.CSharp.RuntimeBinder.Binder.GetMember(0, member, scope, new CSharpArgumentInfo[]{CSharpArgumentInfo.Create(0, null)});
DynamicMetaObject ret = mobj.BindGetMember(binder);
BlockExpression final = Expression.Block(
Expression.Label(CallSiteBinder.UpdateLabel),
ret.Expression
);
LambdaExpression lambda = Expression.Lambda(final, param);
Delegate del = lambda.Compile();
return del.DynamicInvoke(o);
}else{
return o.GetType().GetProperty(member, BindingFlags.Public | BindingFlags.Instance).GetValue(o, null);
}
}
#4
5
string json = w.JSON;
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
DynamicJsonConverter.DynamicJsonObject obj =
(DynamicJsonConverter.DynamicJsonObject)serializer.Deserialize(json, typeof(object));
Now obj._Dictionary
contains a dictionary. Perfect!
现在obj。_Dictionary包含一个字典。完美!
This code must be used in conjunction with Deserialize JSON into C# dynamic object? + make the _dictionary variable from "private readonly" to public in the code there
该代码必须与反序列化JSON一起使用到c#动态对象中?+使_dictionary变量从“private readonly”变为公共代码。
#5
2
Did you see ExpandoObject class?
您看到ExpandoObject类了吗?
Directly from MSDN description: "Represents an object whose members can be dynamically added and removed at run time."
直接从MSDN描述:“表示一个对象,其成员可以在运行时动态添加和删除。”
With it you can write code like this:
你可以这样写代码:
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary<String, Object>)employee).Remove("Name");
#6
0
Thought this might help someone in the future.
认为这对未来的人有帮助。
If you know the property name already, you can do something like the following:
如果您已经知道了属性名称,您可以做如下操作:
[HttpPost]
[Route("myRoute")]
public object SomeApiControllerMethod([FromBody] dynamic args){
var stringValue = args.MyPropertyName.ToString();
//do something with the string value. If this is an int, we can int.Parse it, or if it's a string, we can just use it directly.
//some more code here....
return stringValue;
}
#7
0
IF d was created by Newtonsoft you can use this to read property names and values:
如果d是由Newtonsoft创建的,您可以使用它来读取属性名和值:
foreach (JProperty property in d)
{
DoSomething(property.Name, property.Value);
}
#8
0
C# - How to get Property Name and Value of a dynamic object? C# - Dynamic Object
c# -如何获取动态对象的属性名和值?c# -动态对象
Use the following code to get Name and Value of a dynamic object's property.
使用以下代码获取动态对象属性的名称和值。
dynamic d = new { Property1= "Value1", Property2= "Value2"};
var properties = d.GetType().GetProperties();
foreach (var property in properties)
{
var PropertyName=property.Name;
//You get "Property1" as a result
var PropetyValue=d.GetType().GetProperty(property.Name).GetValue(d, null);
//You get "Value1" as a result
// you can use the PropertyName and Value here
}
#1
81
I don't know if there's a more elegant way with dynamically created objects, but using plain old reflection should work:
我不知道动态创建对象是否有更优雅的方式,但是使用普通的旧反射应该工作:
var nameOfProperty = "property1";
var propertyInfo = myObject.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);
GetProperty
will return null
if the type of myObject
does not contain a public property with this name.
如果myObject类型不包含具有此名称的公共属性,则GetProperty将返回null。
EDIT: If the object is not a "regular" object but something implementing IDynamicMetaObjectProvider
, this approach will not work. Please have a look at this question instead:
编辑:如果对象不是“常规”对象,而是实现IDynamicMetaObjectProvider的东西,则此方法将不起作用。请看看这个问题:
- How do I reflect over the members of dynamic object?
- 如何反映动态对象的成员?
#2
18
This will give you all property names and values defined in your dynamic variable.
这将给您提供在动态变量中定义的所有属性名和值。
dynamic d = { // your code };
object o = d;
string[] propertyNames = o.GetType().GetProperties().Select(p => p.Name).ToArray();
foreach (var prop in propertyNames)
{
object propValue = o.GetType().GetProperty(prop).GetValue(o, null);
}
#3
18
Hope this would help you:
希望这对你有帮助:
public static object GetProperty(object o, string member)
{
if(o == null) throw new ArgumentNullException("o");
if(member == null) throw new ArgumentNullException("member");
Type scope = o.GetType();
IDynamicMetaObjectProvider provider = o as IDynamicMetaObjectProvider;
if(provider != null)
{
ParameterExpression param = Expression.Parameter(typeof(object));
DynamicMetaObject mobj = provider.GetMetaObject(param);
GetMemberBinder binder = (GetMemberBinder)Microsoft.CSharp.RuntimeBinder.Binder.GetMember(0, member, scope, new CSharpArgumentInfo[]{CSharpArgumentInfo.Create(0, null)});
DynamicMetaObject ret = mobj.BindGetMember(binder);
BlockExpression final = Expression.Block(
Expression.Label(CallSiteBinder.UpdateLabel),
ret.Expression
);
LambdaExpression lambda = Expression.Lambda(final, param);
Delegate del = lambda.Compile();
return del.DynamicInvoke(o);
}else{
return o.GetType().GetProperty(member, BindingFlags.Public | BindingFlags.Instance).GetValue(o, null);
}
}
#4
5
string json = w.JSON;
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
DynamicJsonConverter.DynamicJsonObject obj =
(DynamicJsonConverter.DynamicJsonObject)serializer.Deserialize(json, typeof(object));
Now obj._Dictionary
contains a dictionary. Perfect!
现在obj。_Dictionary包含一个字典。完美!
This code must be used in conjunction with Deserialize JSON into C# dynamic object? + make the _dictionary variable from "private readonly" to public in the code there
该代码必须与反序列化JSON一起使用到c#动态对象中?+使_dictionary变量从“private readonly”变为公共代码。
#5
2
Did you see ExpandoObject class?
您看到ExpandoObject类了吗?
Directly from MSDN description: "Represents an object whose members can be dynamically added and removed at run time."
直接从MSDN描述:“表示一个对象,其成员可以在运行时动态添加和删除。”
With it you can write code like this:
你可以这样写代码:
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary<String, Object>)employee).Remove("Name");
#6
0
Thought this might help someone in the future.
认为这对未来的人有帮助。
If you know the property name already, you can do something like the following:
如果您已经知道了属性名称,您可以做如下操作:
[HttpPost]
[Route("myRoute")]
public object SomeApiControllerMethod([FromBody] dynamic args){
var stringValue = args.MyPropertyName.ToString();
//do something with the string value. If this is an int, we can int.Parse it, or if it's a string, we can just use it directly.
//some more code here....
return stringValue;
}
#7
0
IF d was created by Newtonsoft you can use this to read property names and values:
如果d是由Newtonsoft创建的,您可以使用它来读取属性名和值:
foreach (JProperty property in d)
{
DoSomething(property.Name, property.Value);
}
#8
0
C# - How to get Property Name and Value of a dynamic object? C# - Dynamic Object
c# -如何获取动态对象的属性名和值?c# -动态对象
Use the following code to get Name and Value of a dynamic object's property.
使用以下代码获取动态对象属性的名称和值。
dynamic d = new { Property1= "Value1", Property2= "Value2"};
var properties = d.GetType().GetProperties();
foreach (var property in properties)
{
var PropertyName=property.Name;
//You get "Property1" as a result
var PropetyValue=d.GetType().GetProperty(property.Name).GetValue(d, null);
//You get "Value1" as a result
// you can use the PropertyName and Value here
}