General enforcement

I have a common class

public MyClass<TContext, T> where TContext : DataContext

which effectively acts on an instance of another

public class MyOtherClass<T> : IEnumerable<T>

I want to ensure that I TContexthave Table<T>. Is there a clean way to provide this?

+3
source share
3 answers

Do you want to verify that TContext has an element that is a <T> table? If so, the only way to do this is to define an interface for this contract and change your general restrictions

interface IMyTable<T> {
  Table<T> Table;
}

public MyClass<TContext,T> where TContext : DataContext,IMyTable<T>

EDIT

Jason posted an explanatory commentary on my answer. The name table is not static; it depends on type T.

. , , , IMyTable < gt; DataContext Table.

interface IMyTable2<T> {
  DataContext DataContext {get; }
  Table<T> Table {get; }
}

class MyAdapter: IMyTable2<T> {
  private MyOtherClass<T> _other;
  public DataContext DataContext { get { return _other.DataContext } }
  public Table<T> Table { get { return _other.TableWithDifferentName; } }
}
+6

, JaredPar .

interface IMyTable<T>
{
  Table<T> TheTable {get;}
}

public class MyClass<TContext,T> where
  TContext : DataContext,IMyTable<T>
{
  //silly implementation provided to support the later example:
  public TContext Source {get;set;}

  public List<T> GetThem()
  {
    IMyTable<T> x = Source as IMyTable<T>;
    return x.TheTable.ToList(); 
  }
}

, . IMyTable. - , IMyTable<T>, .

public partial class MyDataContext:IMyTable<Customer>, IMyTable<Order>
{
  Table<Customer> IMyTable<Customer>.TheTable
  { get{ return this.GetTable<Customer>(); } }

  Table<Order> IMyTable<Order>.TheTable
  { get{ return this.GetTable<Order>(); } }  
}

:

var z = new MyClass<MyDataContext, Customer>();
z.Source = new MyDataContext();
List<Customer> result = z.GetThem();
+1

the only way to enforce it: if the table was in the interface and you set a general constraint ... so something like

public class MyOtherClass<T> : IEnumerable<T>, IHasTable<T>
-1
source

Source: https://habr.com/ru/post/1702148/


All Articles