[英]Using reflection to set properties for wcf datacontract
我有一個wcf服務,可通過客戶端的wsdl文件動態調用wcf服務。 現在,我想在wcf服務中設置方法的屬性。 我有屬於復雜類型的屬性,在每個復雜類型中,我都有30到4個復雜類型。 我無法接觸該服務,只有一件事是對服務數據合同使用反射關聯值,並使用methodInfo.Invoke(傳遞構造的對象數組)。 客戶端將在字典中傳遞數據合同的輸入參數。 遞歸是否需要瀏覽復雜類型的內部類並設置值。 樣例代碼:
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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.