我在這裏死去,試圖用我的工作單元實現通用存儲庫。這將與我正在進行的特定項目配合使用。但我無法掌握正確的語法。如果我只能得到下面的工作爲出發點......在運行時創建未知類型的通用存儲庫
我希望能夠做一個
unit_of_work.Repository<don't-know-until-runtime>().Insert(run-time-object);
,我不會知道,直到在運行什麼樣的對象我將處理,我只知道它將是類型'BaseClass'。
非常感謝您的幫助。下面我試着把代碼燒掉。
public class BaseClass
{
}
public class SubClass1 : BaseClass
{
public SubClass1()
: base()
{
}
}
public interface IRepository<TEntity> where TEntity : class
{
void Insert(TEntity entity);
}
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
public void Insert(TEntity entity)
{
System.Diagnostics.Debug.WriteLine("got here!!");
}
}
public class UnitOfWork
{
public virtual IRepository<TEntity> Repository<TEntity>() where TEntity : class
{
var type = typeof(TEntity).Name;
var repositoryType = typeof(Repository<>);
return (IRepository<TEntity>) Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)));
}
}
class Program
{
static void Main(string[] args)
{
UnitOfWork unit_of_work = new UnitOfWork();
SubClass1 testClass1 = new SubClass1();
// this works fine, when I know the type in advance...
unit_of_work.Repository<SubClass1>().Insert(testClass1);
// ... but when I don't know the type, then what?
// (All I know is that the incoming object will be of type BaseClass)
}
}
is this C++?你能否用語言標記問題? – Bohemian
@Bohemian我可以和我有,謝謝。 –
我*通常*發現當有人走「我不會知道這裏的類型」時,那麼設計中還有其他的東西是錯的。注我說**通常是**。 –