通过动态密钥名称获取属性?

问题描述 投票:1回答:1

我试图避免重复一些模板,假设我有以下(非常简化)模板:

<div class="same-template">
    @(button?.buttonLeft.Url)
</div>
<div class="same-template">
    @(button?.buttonRight.Url)
</div>

我也有一个按钮右模板,所以我的问题是,有没有办法可以传递按钮的“侧面”,并访问属性?我知道在javascript中我会做类似的事情:

@(button?.button"+side+".Url)但显然我们没有使用javascript。

我试过创建一个辅助函数

@helper GetFooter(Object button, String side) {
    <div class="same-template">
        <!-- don't know what to do here... -->
        @(button?.button<side>.Url)
    </div>
}

@GetFooter(button, "Right")

我希望这很清楚!

编辑:香港专业教育学院做了以下功能,但在一些它在var b线上失败,出现以下错误:

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

@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# razor
1个回答
1
投票

C#是键入的,不提供像JavaScript这样的功能。无论如何,你可以尝试类似于下面的例子来通过名称来阅读财产的价值:

<div>
    @(button?.GetType().GetProperty("PropertyNameWhichYouNeed").GetValue(button, null))
</div>

更新:

好吧,我认为你需要一些扩展方法,但先试试这个:

button?.GetType().GetProperty("buttonRight").GetValue(button, null)
    .GetType().GetProperty("Url").GetValue(
button?.GetType().GetProperty("buttonRight").GetValue(button, null),
 null);

它变得令人困惑:)我不喜欢这种UI,但试着解释一下:

冷杉我检索buttonRight属性的类型。然后我检索类型Url并提供buttonRight实例的类型。

它应该按以下几行划分:

var buttonRight = button.GetType().GetProperty("buttonRight").GetValue(button, null);
var url = buttonRight.GetType().GetProperty("Url").GetValue(buttonRight, null);

现在url是你看的价值。请看小提琴是如何工作的:

.NET Fiddle

© www.soinside.com 2019 - 2024. All rights reserved.