[英]Print a variable on the screen using Razor (C#)
I want to print a variable on the screen using Razor. 我想使用Razor在屏幕上打印一个变量。 I have a class named CustomPrincipal saved in the HttpContext, which is saved correctly.
我在HttpContext中保存了一个名为CustomPrincipal的类,该类已正确保存。
I want it to have it on one line like the example below, which is unfortunately not working: 我希望它像下面的示例一样放在一行上,但不幸的是无法正常工作:
@* This is not working... *@
@(CustomPrincipal)Context.Items["IUser"].Name
The example below is working though, so it saved it correctly to the HttpContext. 但是,下面的示例正在运行,因此可以将其正确保存到HttpContext中。
@{ CustomPrincipal user = (CustomPrincipal)Context.Items["IUser"]; }
@user.Name
Does anyone know why the first example is not working and can you show me a solution? 有谁知道为什么第一个示例不起作用,您能告诉我一个解决方案吗?
The error is: 错误是:
Compiler Error Message: CS0118: 'CustomPrincipal' is a 'type' but is used like a 'variable'
编译器错误消息:CS0118:“ CustomPrincipal”是“类型”,但其用法类似于“变量”
All the credits go to @DavidG and @CodeCaster, mentioned in the comments. 所有的功劳归于注释中提到的@DavidG和@CodeCaster。
@(((CustomPrincipal)Context.Items["IUser"]).Name)
The parentheses where required because otherwise there is no Name
property on the Object
type which is what Context.Items["IUser"]
is. 括号在需要的地方,因为否则在
Context.Items["IUser"]
的Object
类型上没有Name
属性。 We have to add parentheses to cast that Object
to CustomPrincipal
first, then access the Name
property of that type. 我们必须添加括号以首先将该
Object
为CustomPrincipal
,然后访问该类型的Name
属性。
Another example of the same problem: https://stackoverflow.com/a/4151988/4585226 相同问题的另一个示例: https : //stackoverflow.com/a/4151988/4585226
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.