asp.net MVC3剃刀语法反射投模式,它的子类 [英] asp.net mvc3 razor syntax to cast a model to its subclass by reflection

查看:127
本文介绍了asp.net MVC3剃刀语法反射投模式,它的子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很简单的问题,我无法找到答案。
在剃刀认为有接口类型的模型。该接口有多个子类实现它。
现在的问题是:我怎么能投的模式,它的实际类型的?
我必须有实际类型的变量,但不知道如何从反射得到它
即。

I have very simple question that I cannot find the answer to. In the razor view there's a Model of interface type. That interface have multiple subclasses implementing it. The question is: How can I cast the model to its actual type? I MUST have variable of actual type but don't know how to get it from the reflection I.E.

@model IInterface
@{
   var actualType1 = Model as Model.GetType(); // doesn't work :(
   var actualType2 = (Model.GetType()) Model; // doesn't work :(
}

你可以想象我没有兴趣在型号为ActualType (ActualType)型号,因为我不知道什么实际类型提前到来。其对技术,而不是架构的问题。

As you can imagine I am not interested in Model as ActualType or (ActualType) Model because I don't know what actual type is coming in advance. Its a question about the technique rather than architecture.

在此先感谢!

推荐答案

您是真的在这里了错误的道路上。你真的不能做你要找在这里做,因为你并没有真正通过思前想什么。像这样的语句:

You are really on the wrong path here. You can't really do what you're looking to do here, because you are not really thinking it through. A statement like this:

var actualType1 = Model as Model.GetType(); 

不会起作用,因为变种是不是动态类型,它是在编译时输入的,而不是在运行时的静态类型。所以,即使你能够以某种方式设法得到它的工作,也只是一种类型,以往的工作(直到它再次被重新编译)。

Won't work because var is not a dynamic type, it's a static type that is typed at compile time, not at runtime. So even if you could somehow manage to get it to work, it would only work for one type, ever (until it was recompiled again).

除此之外,接口是这个糟糕的选择,因为接口属性从实施单独的属性。所以,不管什么属性你有你的课,你将不会通过该类的接口得到它们。

In addition to that, interfaces are a poor choice for this, because interface attributes are seperate from implementation attributes. So regardless of what attributes you have on your classes, you will not get them via an interface to that class.

这篇关于asp.net MVC3剃刀语法反射投模式,它的子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆