匿名型かどうかの判定

Ver.2に着手したものの、デザインがちょっとな〜な今日この頃ですが(´д`;)
まあ、それとはまったく関係なく、ちょい小ネタ(・∀・)


メソッドの引数に、匿名型をLLよろしく連想配列のように使う場合がありますが。
例えばこんなメソッドを用意しておいて。

public static int DeleteByPK<TEntity>(this Table<TEntity> table, object primaryKey) where TEntity : class

こんな感じで使用する場合。

// Sample1テーブルのPKは1つ
context.Sample1.DeleteByPK( 1 );

// Sample2テーブルのPKはNoとDetailNoの2つ
context.Sample2.DeleteByPK( new { No =123, DetailNo = 456 } );

引数をobject型にしておいて、中身が値型だったらその値を使用して、匿名型だったらそのプロパティを引数にするようなケースで、object型が匿名型かどうかのチェックをしたい場合について。
判定方法としては、以下のやり方が一般的で良いのかな(・∀・)?

public static bool IsAnonymous(this Type type)
{
    return Attribute.IsDefined( type, typeof(CompilerGeneratedAttribute), false ) &&
           type.IsGenericType &&
           type.Name.Contains( "AnonymousType" ) &&
           ( type.Name.StartsWith( "<>" ) || type.Name.StartsWith( "VB$" ) ) &&
           ( ( type.Attributes & TypeAttributes.NotPublic ) == TypeAttributes.NotPublic ) &&
           ( ( type.Attributes & TypeAttributes.Sealed ) == TypeAttributes.Sealed );
}

もうちょっと手を抜いても大丈夫な気もするけれど、とりあえずこれを使っています。


LINQ to SQLも、DeleteByPK()をはじめ、Delete、Update処理の拡張メソッドを用意しておかないとチト不便なのよね〜(´Д`)