-2

私が書きたいこのメソッドがあります:

public static IQueryable<TSource> CutTo<TSource>(this IQueryable<TSource> source, Func<int> func)
{
    int index = func();
    // here I can write something for all types or switch all
    // the types and write code for every type
}

すべての TSource タイプに対してこれをコーディングする最も簡単な方法は何ですか?

編集: Black Bear は、これはすべてのタイプで既に機能すると書いていますが、これは正しくありません。モノは次のように書いています。

public static IQueryable<TSource> Where<TSource> (this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
{
    Check.SourceAndPredicate (source, predicate);

    return source.Provider.CreateQuery<TSource> (
        StaticCall (
            MakeGeneric (MethodBase.GetCurrentMethod (), typeof (TSource)),
            source.Expression,
            Expression.Quote (predicate)));
}
4

1 に答える 1

1

最初の解決策 (よりクリーンな解決策)

特定のインターフェイスを実装する型でのみ機能します

インターフェイスの作成IHaveId

public interface IHaveId
{
    int Id { get; set; }
}

次に、適切なモデルはIdすべて実装する必要がありますIHaveId。例

public class Post : IHaveId
{
    int Id { get; set; }
    string Title { get; set; }
    string Content { get; set; }
}

そして、次のようにCutToメソッドを記述します。

public static IQueryable<T> CutTo<T>(this IQueryable<T> source, Func<int> func)
    where T: IHaveId
{
    int index = func();
    return source.Where(x => x.Id == index);
}

アイデアは、のすべての実装に呼び出さIHaveIdれるintプロパティがあり、メソッドを実装でのみ機能し、それらのプロパティを使用するようにId制限できるということです。CutToIHaveIdId

2番目の解決策(醜い)

主キーの命名に関する Entity Framework 規則を保持する任意の型で動作します

  1. リフレクションオーバーを使用して、またはtypeof(TSource)という名前のプロパティを見つけますIdtypeof(TSource).Name + "Id"
  2. 再びリフレクションを使用して構築し、 with句Expression<Func<TSource, int>>に適用します。IQueryable<T> sourceWhere
于 2015-02-14T16:49:58.083 に答える