[英]casting to base generic class
我的基本控制器如下:
public abstract class BaseController<T, VM> : Controller
where VM : BaseViewModel
where T : Entity
{}
派生控制器如下:
public partial class HomeController : BaseController<Product,ProductViewModel>
{
}
在动作过滤器类中,我想将homecontroller强制转换为基本控制器以访问它不起作用的basecontroller属性。 还是有其他方法可以使用反射来获取基本控制器属性, 有人可以告诉它是否可能吗?
public class DataUpdaterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
**var controller = filterContext.Controller as BaseController;**
} }
尝试这个:
var controller = filterContext.Controller as BaseController<Entity, ViewModel>;
您不能在不知道T是什么的情况下直接将其强制转换为BaseController。 您可以将其转换为实体...
在C#中,给定类似SomeGenericType<T1,T2>
的通用类型,如果您有它的实例,请说
SomeGenericType<int,string> myInstance ;
或者说它的子类型
class MyWidget : SomeGenericType<AbstractWidget,AbstractGadget> { ... }
....
MyWidget widgetInstance ;
如果不了解所涉及的类型参数的详细信息(此处为T1
和T2
),就无法将实例向上转换为继承的实例。 在上面的示例中,虽然您可以将myInstance
SomeGenericType<int,string>
为SomeGenericType<int,string>
并将widgetInstance
为SomeGenericType<AbstractWidget,AbstractGadget>
,但是无法将它们中的任何一个SomeGenericType<?,?>
为SomeGenericType<?,?>
。
这是因为从一般意义上讲,泛型类型的实例并没有真正从基本泛型类型继承。
此外,给出类似
class A { ... }
class B : A { ... }
SomeGenericType<B> instance ;
您甚至不能像这样修改instance
:
SomeGenericType<A> upcast = (SomeGenericType<A>) instance ;
很多时候,我并不特别在意泛型类型的类型参数的细节:我发现这在C#的设计中是一个巨大的失败,尽管我确信设计师有其原因。
C#和CTS(通用类型系统)不允许强制转换为类似的开放通用类型。 如果您在BaseController<,>
中具有不依赖于类型参数的属性,则有两个选择:创建一个非通用接口IBaseController
,在其中列出那些属性,并让BaseController<,>
实现此接口,或创建一个非通用的(可能是抽象的) BaseController<,>
基类,并将属性放入此基类。 无论您是否需要BaseController
转换为BaseController
这都是一个好主意。
顺便说一句,有时您还可以创建属性的非泛型版本,其类型取决于类型参数,例如,在您的情况下, IBaseController
可以具有属性Entity Entity {get;}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.