私はC#の新機能です。オブジェクトのプロパティを反復処理し、すべての空文字列を ""に設定する関数を記述したいと思います。私はそれが "リフレクション"と呼ばれるものを使用して可能であると聞いたことがありますが、私は方法がわかりません。C#でオブジェクトのすべてのプロパティを反復処理する方法は?
おかげ
私はC#の新機能です。オブジェクトのプロパティを反復処理し、すべての空文字列を ""に設定する関数を記述したいと思います。私はそれが "リフレクション"と呼ばれるものを使用して可能であると聞いたことがありますが、私は方法がわかりません。C#でオブジェクトのすべてのプロパティを反復処理する方法は?
おかげ
public class Foo
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public int Prop3 { get; set; }
}
class Program
{
static void Main(string[] args)
{
var foo = new Foo();
// Use reflection to get all string properties
// that have getters and setters
var properties = from p in typeof(Foo).GetProperties()
where p.PropertyType == typeof(string) &&
p.CanRead &&
p.CanWrite
select p;
foreach (var property in properties)
{
var value = (string)property.GetValue(foo, null);
if (value == null)
{
property.SetValue(foo, string.Empty, null);
}
}
// at this stage foo should no longer have null string properties
}
}
foreach(PropertyInfo pi in myobject.GetType().GetProperties(BindingFlags.Public))
{
if (pi.GetValue(myobject)==null)
{
// do something
}
}
object myObject; PropertyInfo[] properties = myObject.GetType().GetProperties(BindingFlags.Instance);
をやって、かなり奇妙なことのように聞こえるhttp://msdn.microsoft.com/en-us/library/aa332493(VS.71).aspx
を参照してください。私はあなたがそれで達成しようとしていることを知りたいのですか? – andynormancx
メモでは、null文字列を ""ではなく "String.Empty"に設定することを検討することをお勧めします。実際の影響は無視できるものですが、効率的なコードのために、前者は新しいオブジェクトを作成しません。 – Cranialsurge
また、私はandynormancxと同意します....あなたの目的は何ですか? – Cranialsurge