如何通过 ref 将参数传递给成员变量?
How do I pass a parameter by ref to a member variable?
C# 很新,从很久以前就有 C++ 背景,所以我似乎很难从 C# 中的指针过渡到 ref。
我有一个 class (EColour),它是我使用所示的构造函数创建的。
我将对 cellTemplate 的引用分配(或至少尝试)给变量 m_template。
在调试中查看,在构建时,m_template 绝对不是空的。
然而,当我开始处理 OnMouseClick 事件时,我得到了一个 null 异常错误,因为 m_template 神奇地变成了 null。
任何人都可以阐明我做错了什么以及如何解决它吗?
public EColour(ref ICellTemplate cellTemplate)
{
m_template = (ColourTemplate)cellTemplate;
}
protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
{
ColorDialog dlg = new ColorDialog();
dlg.AnyColor = m_template.AnyColour; // This throws an exception because m_template is null
base.OnMouseClick(e);
}
ColourTemplate m_template;
在 C# 中,我们有两种主要类型:
value type - its all digit types (int, float, double, long ...)
reference type -its types that inherited from object
ICellTemplate
是引用 class。所以你需要什么 - 只需将它作为常规变量发送到参数中即可。
public class EColour
{
private ColourTemplate m_tamplate;
public EColour(ICellTemplate cellTemplate)
{
m_template = (ColourTemplate)cellTemplate;
}
}
C# 很新,从很久以前就有 C++ 背景,所以我似乎很难从 C# 中的指针过渡到 ref。
我有一个 class (EColour),它是我使用所示的构造函数创建的。
我将对 cellTemplate 的引用分配(或至少尝试)给变量 m_template。
在调试中查看,在构建时,m_template 绝对不是空的。
然而,当我开始处理 OnMouseClick 事件时,我得到了一个 null 异常错误,因为 m_template 神奇地变成了 null。
任何人都可以阐明我做错了什么以及如何解决它吗?
public EColour(ref ICellTemplate cellTemplate)
{
m_template = (ColourTemplate)cellTemplate;
}
protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
{
ColorDialog dlg = new ColorDialog();
dlg.AnyColor = m_template.AnyColour; // This throws an exception because m_template is null
base.OnMouseClick(e);
}
ColourTemplate m_template;
在 C# 中,我们有两种主要类型:
value type - its all digit types (int, float, double, long ...)
reference type -its types that inherited from object
ICellTemplate
是引用 class。所以你需要什么 - 只需将它作为常规变量发送到参数中即可。
public class EColour
{
private ColourTemplate m_tamplate;
public EColour(ICellTemplate cellTemplate)
{
m_template = (ColourTemplate)cellTemplate;
}
}