オブジェクトをWCFサービスに保存するための本当に汎用的なクラスを作成したいと思います。あらゆるタイプのオブジェクトを取得し、リフレクションを介してオブジェクトのプロパティを分析します。オブジェクトをサービスコンテキストに保存するとき、プロパティののSetLink(...)
メソッドを呼び出す必要があるかどうかを知る必要がありDataServiceContext
ます。
したがって、呼び出す必要があるかどうかを確認するためのメソッドが必要SetLink(...)
です。私はすでに自分でやろうとしました:
private bool IsLinkedProperty(PropertyInfo propertyInfo)
{
return (propertyInfo != null) && propertyInfo.PropertyType.IsClass;
}
ただし、この関数は文字列プロパティでは機能せず、他のプロパティでも機能しない可能性があります。誰かがこれに合う機能を持っていますか?
私は次の解決策に行き着きました。ネイサン・リドリーの質問にヒントを見つけました:
/// <summary>
/// Helper class for analyzing a type.
/// </summary>
public static class TypeAnalyzer
{
/// <summary>
/// Calculates if the given type is a "simple" type.
/// </summary>
/// <param name="type">Type to be checked for simplicity.</param>
/// <returns>True, if the type is "simple";false otherwise.</returns>
/// <remarks>
/// The following types are assumed to be simple:
/// <list type="*">
/// <item>string</item>
/// <item>int</item>
/// <item>decimal</item>
/// <item>float</item>
/// <item><see cref="StringComparison"/> (enum type)</item>
/// <item>int? (nullable simple types)</item>
/// </list>
/// The following types are not simple:
/// <list type="*">
/// <item>Point (struct)</item>
/// <item>Point? (nullable struct)</item>
/// <item>StringBuilder (class)</item>
/// </list>
/// </remarks>
public static bool IsSimple(this Type type)
{
if (IsNullableType(type))
return IsNestedTypeSimple(type);
return type.IsPrimitive
|| type.IsEnum
|| type.Equals(typeof(string))
|| type.Equals(typeof(decimal))
|| type.Equals(typeof(DateTime))
|| type.Equals(typeof(Guid));
}
private static bool IsNestedTypeSimple(Type type)
{
var nestedType = Nullable.GetUnderlyingType(type);
return IsSimple(nestedType);
}
private static bool IsNullableType(Type type)
{
return Nullable.GetUnderlyingType(type) != null;
}
}
NUnitで記述されたテストケースは次のとおりです。
[TestFixture]
public class TypeAnalyzerTests
{
[TestCase(typeof(string), true)]
[TestCase(typeof(int), true)]
[TestCase(typeof(decimal), true)]
[TestCase(typeof(float), true)]
[TestCase(typeof(StringComparison), true)]
[TestCase(typeof(int?), true)]
[TestCase(typeof(decimal?), true)]
[TestCase(typeof(StringComparison?), true)]
[TestCase(typeof(object), false)]
[TestCase(typeof(Point), false)]
[TestCase(typeof(Point?), false)]
[TestCase(typeof(StringBuilder), false)]
[TestCase(typeof(DateTime), true)]
[TestCase(typeof(Guid), true)]
[TestCase(typeof(Guid?), true)]
public void IsSimple_WhenCalledForType_ReturnsExpectedResult(Type type, bool expectedResult)
{
var isSimple = TypeAnalyzer.IsSimple(type);
Assert.That(isSimple, Is.EqualTo(expectedResult));
}
}
最後に、質問で言及した方法を次のように変更しました。
private bool IsLinkedProperty()
{
return (_propertyInfo != null) && !_propertyInfo.PropertyType.IsSimple();
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加