gpt4 book ai didi

c# - 使用反射为 wcf datacontract 设置属性

转载 作者:太空宇宙 更新时间:2023-11-03 16:03:41 29 4
gpt4 key购买 nike

我有一个wcf服务,在客户端通过wsdl文件动态调用wcf服务。现在我想在我的 wcf 服务中设置一个方法的属性。我有复杂类型的属性,在每个复杂类型中我有 30 到 4o 个复杂类型。我无法触及该服务,唯一的事情是使用反射将值分配给服务数据契约(Contract)并使用 methodInfo.Invoke(传递构造的对象数组)。客户端将在字典中传递数据契约(Contract)的输入参数。递归是否需要在复杂类型的内部类中导航并设置值。 示例代码:

 public CompositeType GetTestDataUsingDataContract(CompositeType composite, string str, int i,EmployeeIn obj)
{
///code here
}
**DataContract for CompositeType**
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
EmployeeIn employeeValue;
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}

[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
[DataMember]
public EmployeeIn EmploValue
{
get { return employeeValue; }
set { employeeValue = value; }
}
}
EmployeeIn Class
[DataContract]
public class EmployeeIn
{
bool UserIsOnline = true;
string UserName = "DANGER";

[DataMember]
public bool BoolValue
{
get { return UserIsOnline; }
set { UserIsOnline = value; }
}

[DataMember]
public string StringValue
{
get { return UserName; }
set { UserName = value; }
}
}

我想使用反射来设置这些属性。

最佳答案

这是一个通过反射设置属性的工作代码,属性名称由字符串提供:

void SetPropertyValue(object obj, string propertyPath, object value)
{
System.Reflection.PropertyInfo currentProperty = null;
string[] pathSteps = propertyPath.Split('/');
object currentObj = obj;
for (int i = 0; i < pathSteps.Length; ++i)
{
Type currentType = currentObj.GetType();
string currentPathStep = pathSteps[i];
var currentPathStepMatches = Regex.Match(currentPathStep, @"(\w+)(?:\[(\d+)\])?");
currentProperty = currentType.GetProperty(currentPathStepMatches.Groups[1].Value);
int arrayIndex = currentProperty.PropertyType.IsArray ? int.Parse(currentPathStepMatches.Groups[2].Value) : -1;
if (i == pathSteps.Length - 1)
{
currentProperty.SetValue(currentObj, value, arrayIndex > -1 ? new object[] { arrayIndex } : null);
}
else
{
if (currentProperty.PropertyType.IsArray)
{
currentObj = (currentProperty.GetValue(currentObj) as Array).GetValue(arrayIndex);
}
else
{
currentObj = currentProperty.GetValue(currentObj);
}
}
}
}

现在您可以使用此函数来设置属性,例如:

SetPropertyValue(someClass, "SomeInt", 4);
SetPropertyValue(someClass, "ArrayProperty[5]/Char", (char)2);
SetPropertyValue(someClass, "TestField", new SomeOtherClass());

关于c# - 使用反射为 wcf datacontract 设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303056/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com