string
作成したクラスのインスタンスを分析し、そのクラスの各プロパティの型をチェックし、それらのstring
プロパティがnull
空かどうかをチェックするメソッドを作成しています。
コード:
public class RootClass
{
public string RootString1 { get; set; }
public string RootString2 { get; set; }
public int RootInt1 { get; set; }
public Level1ChildClass1 RootLevel1ChildClass11 { get; set; }
public Level1ChildClass1 RootLevel1ChildClass12 { get; set; }
public Level1ChildClass2 RootLevel1ChildClass21 { get; set; }
}
public class Level1ChildClass1
{
public string Level1String1 { get; set; }
public string Level1String2 { get; set; }
public int Level1Int1 { get; set; }
}
public class Level1ChildClass2
{
public string Level1String1 { get; set; }
public string Level1String2 { get; set; }
public int Level1Int1 { get; set; }
public Level2ChildClass1 Level1Level2ChildClass11 { get; set; }
public Level2ChildClass1 Level1Level2ChildClass12 { get; set; }
public Level2ChildClass2 Level1Level2ChildClass22 { get; set; }
}
public class Level2ChildClass1
{
public string Level2String1 { get; set; }
public string Level2String2 { get; set; }
public int Level2Int1 { get; set; }
}
public class Level2ChildClass2
{
public string Level2String1 { get; set; }
public string Level2String2 { get; set; }
public int Level2Int1 { get; set; }
}
クラスのすべてのプロパティが文字列であるとは限りません。それらの一部は、同じ方法で分析する必要がある独自のプロパティを持つ他のクラスのインスタンスです。基本的にtrue
、プロパティのいずれかが RootClass またはクラスのサブレベルの任意の場所に値を持つ文字列である場合 (たとえば、RootLevel1ChildClass11
値を持つ文字列プロパティがある場合)、メソッドは戻ります。
これが私がこれまでに持っているものです:
public static bool ObjectHasStringData<T>(this T obj)
{
var properties = typeof(T).GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var property in properties)
{
Type propertyType = property.PropertyType;
if (propertyType == typeof(string))
{
try
{
if (!String.IsNullOrEmpty(property.GetValue(obj, null) as string))
return true;
}
catch (NullReferenceException) { } // we want to ignore NullReferenceExceptions
}
else if (!propertyType.IsValueType)
{
try
{
if (ObjectHasStringData(property.GetValue(obj, null)))
return true;
}
catch (NullReferenceException) { } // we want to ignore NullReferenceExceptions
}
}
return false;
}
これは最初のレイヤー (string
つまり 内のすべてRootClass
) でうまく機能しますが、行で再帰的に使用し始めるとif (ObjectHasStringData(property.GetValue(obj, null)))
、の戻り値はproperty.GetValue()
isobject
になるため、メソッドを再帰的に呼び出すと、T
is object
.
現在のオブジェクトの を取得できますが、返された をプロパティの実際の型Type
に変換するにはどうすればよいですか?object
property.GetValue()