通常填充不同的类成员我正在开发一个具有数(11)个Web服务调用的Web服务应用程序。对于每个Web服务,我需要从一个字符串数组中填充SoapBody,如下所示:)DCSSCustomerUpdate_V3.Branch].ToString();}aMessage[int]是一个字符串数组,[int]由一个枚举常量定义——在本例中它定义如下:privateenumDCSSCustomerUpdate_V3{MsgType=0,MsgVersion=1,WSName=2,ReplyTo=3,SourceSystem=4,...}部分类中的属性名称与枚举常量匹配,所以我想我也传递了枚举常量?部分类在wsdl中定义如下:publicpartialclassDCSSCustomerUpdateType{privatestringinstIdField;私有字符串分支字段;...}我不知道是否有办法传递分部类wsSoapBody(和一个字符串数组)并循环遍历该类的所有成员,分配值而不是为每个单独执行此操作(在11个自定义服务类)来自字符串数组?编辑:我搜索并找到了SO:531384/how-to-loop-through-all-the-properties-of-class?所以我尝试了这个:publicstaticvoidDisplayAll(Objectobj,string[]aMessage){Typetype=obj.GetType();PropertyInfo[]属性=type.GetProperties();foreach(属性中的PropertyInfo属性){stringvalue=aMessage[property.Name].ToString();系统诊断.Debug.WriteLine("名称:"+property.Name+",值:"+property.GetValue(obj,null));}}但字符串值=aMessage[property.Name].ToString();不会编译-因为它正在寻找从枚举常量返回的int...所以我从这里去哪里?尝试一下DCSSCustomerUpdate_V3t=(DCSSCustomerUpdate_V3)Enum.Parse(typeof(DCSSCustomerUpdate_V3),property.Name);字符串值=aMessage[(int)t].ToString();您还可以对通用枚举使用方法Enum.TryParse类型或多或少是publicstaticvoidDisplayAll(Objectobj,string[]aMessage)whereTEnum:struct,IComparable,IFormattable,IConvertible{if(!typeof(TEnum).IsEnum){thrownewArgumentException("T必须是枚举类型");类型type=obj.GetType();PropertyInfo[]属性=type.GetProperties();foreach(属性中的PropertyInfo属性){TEnumt=(TEnum)Enum.Parse(typeof(TEnum),property.Name);字符串值=aMessage[t.ToInt32(Thread.CurrentThread.CurrentCulture)].ToString();System.Diagnostics.Debug.WriteLine("名称:"+property.Name+",值:"+property.GetValue(obj,null));}}请参阅这篇文章创建一个通用方法以将T限制为一个枚举我不知道我是否理解你的问题:if(aMessage[(int)DCSSCustomerUpdate_V3.Branch]。ToString().Length!=0){wsSoapBody.Branch=aMessage[(int)DCSSCustomerUpdate_V3.Branch].ToString();}所以你有这个枚举DCSCus??tomerUpdate_V3其成员匹配wsSoapBody类的属性名称,你不想像上面那样重复代码,但是使用循环,对吗?您可以简单地遍历DCCSSCustomerUpdate_V3的所有元素并设置属性的值,例如://枚举类型;作为参数传入varenumType=typeof(DCSSCustomerUpdate_V3)//获取wsSoapBody的类型vart=wsSoapBody.GetType();//遍历DCSSCustomerUpdate_V3的所有元素foreach(varvalueinEnum.GetValues(enumType)){if(aMessage[(int)value].ToString().Length!=0){//使用SetValue设置值t.GetProperty(value.ToString()).SetValue(wsSoapBody,aMessage[(int)value].ToString());感谢Fabio和Sloth,这是我们构建的最终代码:publicstaticvoidDisplayAll(Objectobj,string[]aMessage)whereTEnum:struct,IComparable,IFormattable,IConvertible/**seehttps://stackoverflow.com/questions/28168982/generally-populate-different-classes-members**/{try{//获取wsSoapBody的类型Typetype=obj.GetType();PropertyInfo[]属性=type.GetProperties();foreach(属性中的PropertyInfo属性){System.Diagnostics.Debug.WriteLine("名称:"+property.Name+",值:"+property.GetValue(obj,null)+"类型:"+property.PropertyType);//property.GetValue(obj,null)。ToString()!=""&&if(t.ToInt32(Thread.CurrentThread.CurrentCulture)并调用它,我们使用:以上是C#学习教程:通常填写不同类成员共享的所有内容,如果是对大家有帮助有用的,需要详细了解C#学习教程,希望大家多多关注—Common.DisplayAll(wsSoapBody,aMessage);本文收集自网络,不代表立场,如涉及侵权,请点击右侧联系管理员来源:
