C# 通过动态键名获取属性?
我试图避免复制一些模板,假设我有以下(非常简化的)模板:C# 通过动态键名获取属性?,c#,razor,C#,Razor,我试图避免复制一些模板,假设我有以下(非常简化的)模板: <div class="same-template"> @(button?.buttonLeft.Url) </div> <div class="same-template"> @(button?.buttonRight.Url) </div> 我希望这足够清楚 编辑: 我做了以下功能,但在某些情况下,它在var b行失败,出现以下错误: 异常详细信息:System.Nul
<div class="same-template">
@(button?.buttonLeft.Url)
</div>
<div class="same-template">
@(button?.buttonRight.Url)
</div>
我希望这足够清楚
编辑:
我做了以下功能,但在某些情况下,它在var b
行失败,出现以下错误:
异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。
@functions{
public dynamic GetNestedDynamicValue(IContentCardItem cardItem, String first, String second) {
var b = cardItem?.GetType().GetProperty(first).GetValue(cardItem, null);
var c = b?.GetType().GetProperty(second).GetValue(b, null);
return c;
}
}
C#是类型化的,不提供JavaScript之类的功能。不管怎样,您可以尝试以下示例中的方法,通过名称直观地读取属性的值:
<div>
@(button?.GetType().GetProperty("PropertyNameWhichYouNeed").GetValue(button, null))
</div>
它变得令人困惑:)我不喜欢这种UI,但让我们试着解释一下:
首先,我检索按钮右侧属性的类型。然后我检索类型Url
并提供buttonRight
实例的类型
它应该分成以下几行:
var buttonRight = button.GetType().GetProperty("buttonRight").GetValue(button, null);
var url = buttonRight.GetType().GetProperty("Url").GetValue(buttonRight, null);
现在url
是您要查找的值。请参见小提琴的工作原理:
.所以,您想在页面中显示按钮属性的值吗?是否要按字符串名称访问该属性?不支持您访问该属性的方式。您可以做的是检查if子句中侧
的值,并根据该值使用按钮的适当属性。为此,这与我尝试的类似,我完全省略了部分代码,如何访问按钮?.buttonLeft?.Text
,其中左侧仍然是键的动态部分,但是文字是不变的?谢谢你,最后一件事!我用我的上一个问题再次编辑了我的OP我的最新编辑:它看起来无法为第一个
或第二个
构造对象。你能确保这些属性存在吗?你能做一些日志记录或调试吗?这是我的提琴盒:
button?.GetType().GetProperty("buttonRight").GetValue(button, null)
.GetType().GetProperty("Url").GetValue(
button?.GetType().GetProperty("buttonRight").GetValue(button, null),
null);
var buttonRight = button.GetType().GetProperty("buttonRight").GetValue(button, null);
var url = buttonRight.GetType().GetProperty("Url").GetValue(buttonRight, null);