gpt4 book ai didi

c# - 如何使用通用约束进行这种棘手的向下转换?

转载 作者:太空狗 更新时间:2023-10-29 18:21:30 25 4
gpt4 key购买 nike

我正在尝试向下转换 Action 过滤器中的 Controller 实例,但我在这样做时遇到了问题。

我有一个 DefaultController 类:

public abstract partial class DefaultController<T> : Controller where T : IBaseEntity
{

}

IBaseEntity 是:

public interface IBaseEntity
{
int Id { get; set; }
DateTime CreatedOn { get; set; }
DateTime ModifiedOn { get; set; }
int CreatedBy { get; set; }
int ModifiedBy { get; set; }
int OwnerId { get; set; }

}

我有一个 Controller 实例,它继承了 DefaultController:

public class WorkflowController : DefaultController<Workflow>
{
}

Workflow 继承了 BaseEntity 实现了 IBaseEntity

现在,在我的 Action 过滤器中,代码明智,不可能知道请求在哪个 Controller 上运行,所以我试图将它向下转换为 DefaultController

public class AddHeaders : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{

var defaultControllerGenericType = controller.GetType().BaseType.GenericTypeArguments.FirstOrDefault();
//this retrieve with which type DefaultController was initiated with...
var controller = filterContext.Controller as DefaultController<BaseEntity>;
//this returns null...
var controller2 = filterContext.Controller as DefaultController<IBaseEntity>;
//this does so as well.

}
}

我试过使用 defaultControllerGenericType 但我无法将它传递到任何地方,或者至少我缺少正确的语法。

有什么办法吗?

最佳答案

理解为什么这是不可能的是有启发意义的。

public abstract partial class DefaultController<T> : Controller where T : IBaseEntity { ... }
public class WorkflowController : DefaultController<Workflow> { ... }

在这里,让我重写一下:

class Container { }
class Animal { }
class Fish : Animal { }
class Cage<T> : Container where T : Animal
{
public T Contents { get; set; }
}
class Aquarium : Cage<Fish> { }

现在的问题是,当我有:

Aquarium a = new Aquarium(); // Fine
Cage<Fish> cf = a; // Fine
Container c = a; // Fine
Cage<Animal> ca1 = a; // Nope
Cage<Animal> ca2 = a as Cage<Animal>; // Null!

为什么不允许这样做?好吧,假设这是允许的。

Cage<Animal> ca = a; // Suppose this is legal
Tiger t = new Tiger(); // Another kind of animal.
ca.Contents = t; // Cage<Animal>.Contents is of type Animal, so this is legal

我们只是把一只老虎放到水族馆里。这就是为什么这是非法的。

正如 Jon Skeet 所说,一碗苹果不是一碗水果。您可以将香蕉放入一碗水果中,但不能将香蕉放入一碗苹果中,因此它们是不同的类型!

关于c# - 如何使用通用约束进行这种棘手的向下转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52599260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com