我正在使用WCF服务
我有数据合同:
[DataContract]
[KnownType(typeof(CustomBranches))]
public class CustomBranches
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string branch_name { get; set; }
[DataMember]
public string address_line_1 { get; set; }
[DataMember]
public string city_name { get; set; }
}
我是否有可能在此课程中找到所有DataMembers的名称 CustomBranches
喜欢“ID”,“分支名称”等
由于
答案 0 :(得分:14)
您需要做什么:
[KnownType(typeof(CustomBranches))]
课程中添加CustomBranches
。一个班级总是知道自己。[DataMember]
属性的属性(nillls代码返回所有属性)这是完成所有这些操作的代码示例。
public class StackOverflow_8152252
{
public static void Test()
{
BindingFlags instancePublicAndNot = BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic;
var memberNames = typeof(CustomBranches)
.GetProperties(instancePublicAndNot)
.OfType<MemberInfo>()
.Union(typeof(CustomBranches).GetFields(instancePublicAndNot))
.Where(x => Attribute.IsDefined(x, typeof(DataMemberAttribute)))
.Select(x => x.Name);
Console.WriteLine("All data member names");
foreach (var memberName in memberNames)
{
Console.WriteLine(" {0}", memberName);
}
}
[DataContract]
public class CustomBranches
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string branch_name { get; set; }
[DataMember]
public string address_line_1 { get; set; }
[DataMember]
public string city_name { get; set; }
public int NonDataMember { get; set; }
[DataMember]
public string FieldDataMember;
[DataMember]
internal string NonPublicMember { get; set; }
}
}
答案 1 :(得分:4)
看到它是一个数据契约,您最有可能拥有所有这些属性,但如果不是,则以下内容应列出您的类型的所有属性:
Type T =(typeof(T));
var properties = T.GetProperties(BindingFlags.Public|BindingFlags.Instance);
用类型替换T,你很高兴。根据您的需要,您可能需要不同的BindingFlags。
答案 2 :(得分:3)
我稍微修改了Carlos的回答,忽略了用[NonSerialized]
属性修饰的数据成员:
public class StackOverflow_8152252
{
public static void Test()
{
BindingFlags instancePublicAndNot = BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic;
var memberNames = typeof(CustomBranches)
.GetProperties(instancePublicAndNot)
.OfType<MemberInfo>()
.Union(typeof(CustomBranches).GetFields(instancePublicAndNot))
.Where(x => Attribute.IsDefined(x, typeof(DataMemberAttribute))
&& !Attribute.IsDefined(x, typeof(NonSerializedAttribute)))
.Select(x => x.Name);
Console.WriteLine("All data member names");
foreach (var memberName in memberNames)
{
Console.WriteLine(" {0}", memberName);
}
}
[DataContract]
public class CustomBranches
{
[DataMember]
public int Id { get; set; }
[DataMember]
[NonSerialized]
public string NonSerializedDataMember { get; set; }
}
}