Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将对象从一个泛型方法(其中T:MyClass)传递到另一个泛型方法(其中T:DerivedClass)_C#_Entity Framework_Inheritance_Polymorphism - Fatal编程技术网

C# 将对象从一个泛型方法(其中T:MyClass)传递到另一个泛型方法(其中T:DerivedClass)

C# 将对象从一个泛型方法(其中T:MyClass)传递到另一个泛型方法(其中T:DerivedClass),c#,entity-framework,inheritance,polymorphism,C#,Entity Framework,Inheritance,Polymorphism,我有一个包含此方法的通用存储库: public void Delete<T>(T item) where T : EntityBase 但这给了我一个错误“无法将类型T转换为SoftDeleteEntityBase” 我如何得到BoL?这个简短的解决方案怎么样,但是考虑改变你的库的设计 SoftDeleteEntityBase itemAsSoft = item as SoftDeleteEntityBase; if (itemAsSoft != null) { itemA

我有一个包含此方法的通用存储库:

public void Delete<T>(T item) where T : EntityBase
但这给了我一个错误
“无法将类型T转换为SoftDeleteEntityBase”


我如何得到BoL?

这个简短的解决方案怎么样,但是考虑改变你的库的设计

SoftDeleteEntityBase itemAsSoft = item as SoftDeleteEntityBase;
if (itemAsSoft != null)
{
    itemAsSoft.Deleted = true;
    Update(itemAsSoft);
}
我不知道您的上下文,但是这个带环绕泛型的解决方案呢

void Main()
{
    Delete(new Base()); // called with base
    Delete(new Derived()); //called with derived
}
public void Delete(Base item)
{
    Console.WriteLine ("called with base");
    //one logic
    GenericDelete(item);
}

public void Delete(Derived item)
{
    Console.WriteLine ("called with derived");
    //another logic
    GenericDelete(item);
}

public void GenericDelete<T>(T item)
{}

public class Base
{}

public class Derived : Base
{}
void Main()
{
Delete(new Base());//用Base调用
Delete(new-Derived());//使用派生函数调用
}
公共作废删除(基本项)
{
Console.WriteLine(“用base调用”);
//一个逻辑
一般删除(项目);
}
公共作废删除(派生项)
{
Console.WriteLine(“使用派生函数调用”);
//另一种逻辑
一般删除(项目);
}
公共作废一般删除(T项)
{}
公共阶级基础
{}
派生的公共类:基
{}

理想情况下,您应该利用多态性。
EntityBase
类可以有一个
Delete
方法;它和其他实现可以选择执行硬删除。
SoftDeleteEntityBase
类可以重写该方法,而不是选择只设置一个
Deleted
字段,而不是硬删除它。那么这里的方法不需要关心派生类型是什么;它可以调用
Delete
,让类自己选择。

我不完全确定这将如何工作。。。该存储库通过实体框架操纵我的数据库,因此我必须将整个数据上下文传递到对象的
Delete
方法中,这在我看来很混乱。(项目为SoftDeleteEntityBase)。Deleted=true@JohnLiu可能
NullReferenceException
谢谢llya,假设在函数开始时检查。不是这句话。@JohnLiu实际上。。。是的,把那条线换掉行得通。我不太清楚我怎么记得我可以在支票中使用
is
,但忘记了我可以在转换中使用
as
。如果你想把它作为一个答案,我会接受的。很好,谢谢。我建议您考虑一下如何处理软删除。看起来您正在将业务逻辑隐藏到基础架构组件中。
void Main()
{
    Delete(new Base()); // called with base
    Delete(new Derived()); //called with derived
}
public void Delete(Base item)
{
    Console.WriteLine ("called with base");
    //one logic
    GenericDelete(item);
}

public void Delete(Derived item)
{
    Console.WriteLine ("called with derived");
    //another logic
    GenericDelete(item);
}

public void GenericDelete<T>(T item)
{}

public class Base
{}

public class Derived : Base
{}