C#:如何获取某个类型的所有公共(包括 get 和 set)字符串属性 [英] C#: How to get all public (both get and set) string properties of a type
问题描述
我正在尝试创建一个方法,该方法将遍历通用对象列表并替换其类型为 string
的所有属性,该属性为 null
或用替换为空.
I am trying to make a method that will go through a list of generic objects and replace all their properties of type string
which is either null
or empty with a replacement.
这样做的好方法是什么?
How is a good way to do this?
我有这种……外壳……到目前为止:
I have this kind of... shell... so far:
public static void ReplaceEmptyStrings<T>(List<T> list, string replacement)
{
var properties = typeof(T).GetProperties( -- What BindingFlags? -- );
foreach(var p in properties)
{
foreach(var item in list)
{
if(string.IsNullOrEmpty((string) p.GetValue(item, null)))
p.SetValue(item, replacement, null);
}
}
}
那么,我如何找到一个类型的所有属性:
So, how do I find all the properties of a type that are:
string
有公开的get
有公开的set
?
我做了这个测试类:
class TestSubject
{
public string Public;
private string Private;
public string PublicPublic { get; set; }
public string PublicPrivate { get; private set; }
public string PrivatePublic { private get; set; }
private string PrivatePrivate { get; set; }
}
以下不起作用:
var properties = typeof(TestSubject)
.GetProperties(BindingFlags.Instance|BindingFlags.Public)
.Where(ø => ø.CanRead && ø.CanWrite)
.Where(ø => ø.PropertyType == typeof(string));
如果我打印出我到达那里的那些属性的名称,我会得到:
If I print out the Name of those properties I get there, I get:
公共公共公私私人公共
换句话说,我得到了太多的两个属性.
In other words, I get two properties too much.
注意:这可能会以更好的方式完成...使用嵌套的 foreach 和反射以及所有这些...但是如果您有任何好的替代想法,请告诉我知道因为我想学习!
Note: This could probably be done in a better way... using nested foreach and reflection and all here... but if you have any great alternative ideas, please let me know cause I want to learn!
推荐答案
您的代码已重写.不使用 LINQ 或 var.
Your code rewritten. Does not use LINQ nor var.
public static void ReplaceEmptyStrings<T>(List<T> list, string replacement)
{
PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo p in properties)
{
// Only work with strings
if (p.PropertyType != typeof(string)) { continue; }
// If not writable then cannot null it; if not readable then cannot check it's value
if (!p.CanWrite || !p.CanRead) { continue; }
MethodInfo mget = p.GetGetMethod(false);
MethodInfo mset = p.GetSetMethod(false);
// Get and set methods have to be public
if (mget == null) { continue; }
if (mset == null) { continue; }
foreach (T item in list)
{
if (string.IsNullOrEmpty((string)p.GetValue(item, null)))
{
p.SetValue(item, replacement, null);
}
}
}
}
这篇关于C#:如何获取某个类型的所有公共(包括 get 和 set)字符串属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!