如何在C#中分配值? [重复]

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

这个问题在这里已有答案:

我正在调查C#和一些代码所在的字符串:

sheet.Cells[startRowIndexHeader, 11].Value = _currentRowPowerContext.HighVoltageSubstationContext.LowSide.Cub.TryGetCaption();

在一些excel单元格中插入一些文本值。当我试图通过字符串更改此Cub时:

currentRowPowerContext.HighVoltageSubstationContext.LowSide.Cub.AttributeCaption = "My value";

我收到了这条消息

对象引用不指向对象的实例

如何改变Cub值?

顺便说一句,我在这个脚本中找到了TryGetCaption()函数的代码:

public static string TryGetCaption(this ClassifierItem value)
{
    return value == null ? null : value.AttributeCaption;
}

public static string TryGetCaption(this DirectRoute value)
{
    var routeAsIp = value as CustomTCPClientRoute;
    if (routeAsIp != null)
        return string.Format("{0}: {1}", routeAsIp.AttributeHostOrIP, routeAsIp.AttributePort);
    return value == null ? null : value.Caption;
}

public static string TryGetCaption(this EnumerationItem value)
{
    return value == null ? null : value.Caption;
}
c# assign
1个回答
0
投票

currentRowPowerContext.HighVoltageSubstationContext.LowSide.Cub为null,因此您无法为其属性赋值。在分配之前检查它是否为空:

if(currentRowPowerContext.HighVoltageSubstationContext.LowSide.Cub != null)
currentRowPowerContext.HighVoltageSubstationContext.LowSide.Cub.AttributeCaption = "My value";
© www.soinside.com 2019 - 2024. All rights reserved.