Asp.net 使用反射设置对象属性的属性
我有两节课Asp.net 使用反射设置对象属性的属性,asp.net,reflection,c#-3.0,Asp.net,Reflection,C# 3.0,我有两节课 public class Class1 { public string value {get;set;} } public class Class2 { public Class1 myClass1Object {get;set;} } 我有一个2类的对象。我需要使用类2上的反射来设置value属性。。。i、 e,如果我在做这件事时没有思考,我会这样做: Class2 myObject = new Class2(); myObject.myClass1Object.v
public class Class1 {
public string value {get;set;}
}
public class Class2 {
public Class1 myClass1Object {get;set;}
}
我有一个2类的对象。我需要使用类2上的反射来设置value属性。。。i、 e,如果我在做这件事时没有思考,我会这样做:
Class2 myObject = new Class2();
myObject.myClass1Object.value = "some value";
在使用反射访问属性“MyClassObject.value”时,是否有方法执行上述操作
提前感谢。基本上将其分为两个属性访问。首先获取
myclassobject
属性,然后对结果设置值
属性
显然,您需要采用任何格式的属性名称,并将其拆分出来-例如,通过点。例如,这将对任意深度的属性执行以下操作:
public void SetProperty(object source, string property, object target)
{
string[] bits = property.Split('.');
for (int i=0; i < bits.Length - 1; i++)
{
PropertyInfo prop = source.GetType().GetProperty(bits[i]);
source = prop.GetValue(source, null);
}
PropertyInfo propertyToSet = source.GetType()
.GetProperty(bits[bits.Length-1]);
propertyToSet.SetValue(source, target, null);
}
public void SetProperty(对象源、字符串属性、对象目标)
{
string[]bits=property.Split('.');
for(int i=0;i
诚然,您可能需要更多的错误检查:)我正在寻找在给定属性名称的情况下获取属性值的答案,但属性的嵌套级别未知 例如,如果输入是“value”,而不是提供一个完全限定的属性名,如“myclassobject.value” 您的回答启发了我下面的递归解决方案:
public static object GetPropertyValue(object source, string property)
{
PropertyInfo prop = source.GetType().GetProperty(property);
if(prop == null)
{
foreach(PropertyInfo propertyMember in source.GetType().GetProperties())
{
object newSource = propertyMember.GetValue(source, null);
return GetPropertyValue(newSource, property);
}
}
else
{
return prop.GetValue(source,null);
}
return null;
}
公共静态对象GetNestedPropertyValue(对象源,字符串属性)
{
PropertyInfo prop=null;
字符串[]props=property.Split('.');
for(int i=0;i
使用标准反射是完全可能的,尽管除非您有通用规则,否则这似乎是一些一次性逻辑,在没有反射的情况下可能会更好。@Quintin我确实意识到我的示例有点做作;然而,我的实际情况实际上比我发布的示例复杂得多,并且确实需要进行反思才能完成。非常好。我已经在这条路上冒险尝试获取第一个属性的PropertyInfo,但是当我试图调用SetValue时遇到了一堵墙,因为我实际上没有源代码(即,您为缺少的部分提供了GetValue)。谢谢谢谢我有一个递归版本。这个实现更好:采用!我尝试过对结构的字段(FieldInfo、Get/SetField等)做一些等效的操作,但没有成功。人们会期望这种行为有所不同吗?例如,结构A包含结构B,结构B包含int i。SetProperty(来源“B.i”,4)不会将a.B.i更改为4。有什么想法吗?@Ryan:此时您将获取属性B
,它将获取该属性的副本,对副本进行变异,但不会将副本分配回B
。基本上,你应该避免易变结构,因为它们会让这类事情变得很痛苦。@JonSkeet谢谢你的回答。这是有道理的。我通过在for循环的堆栈上抛出一些东西(字段和源对象),然后在返回的过程中弹出并赋值来解决这个问题。它可能不漂亮,但它很管用。
public static object GetNestedPropertyValue(object source, string property)
{
PropertyInfo prop = null;
string[] props = property.Split('.');
for (int i = 0; i < props.Length; i++)
{
prop = source.GetType().GetProperty(props[i]);
source = prop.GetValue(source, null);
}
return source;
}