“对象” 不包含“值”
本文关键字:包含 对象 | 更新日期: 2023-09-27 18:31:38
我正在构建一个函数来减少 18 个按钮的相同代码。
这是代码:
void hexagon_Click(object sender, ActionEventArgs e)
{
count++;
this.Dispatcher.Invoke((Action)(() =>
{
sender.RectOne.Fill = sender.Brush;
sender.RectTwo.Fill = sender.Brush;
sender.RectThree.Fill = sender.Brush;
}));
if (count == 1)
{
kliknatopole = sender;
}
else if (count == 2)
{
if (kliknatopole == sender)
{
return;
}
else
{
if (kliknatopole.Brush == sender.brush)
{
levelUpControUI(level);
prepareForNextLevel();
nextLevel1();
count = 0;
sender.Enabled = false;
kliknatopole.Enabled = false;
}
else
{
this.Dispatcher.Invoke((Action)(() =>
{
sender.RectOne.Fill = sender.Brush;
sender.RectTwo.Fill = sender.Brush;
sender.RectThree.Fill = sender.Brush;
}));
Thread.Sleep(500);
this.Dispatcher.Invoke((Action)(() =>
{
sender.RectOne.Fill = Brushes.Transparent;
sender.RectTwo.Fill = Brushes.Transparent;
sender.RectThree.Fill = Brushes.Transparent;
kliknatopole.RectOne.Fill = Brushes.Transparent;
kliknatopole.RectTwo.Fill = Brushes.Transparent;
kliknatopole.RectThree.Fill = Brushes.Transparent;
}));
toLevelOne();
count = 0;
}
}
}
}
现在我不知道为什么,但是kliknatopole
这是一个private object
,sender
无法访问类HexagonControl
的值,这里是:
public partial class HexagonControl : UserControl
{
public BaseControlLogic controlLogic { get; set; }
public HexagonControl()
{
InitializeComponent();
controlLogic = new BaseControlLogic();
}
public Rectangle RectOne { get { return rectOne; } }
public Rectangle RectTwo { get { return rectTwo; } }
public Rectangle RectThree { get { return rectThree; } }
public Brush Brush { set; get; }
}
对于RectOne,Two and Three
,以及Brush
,我收到此错误:
'object' does not contain a definition for 'RectOne' and no extension method 'RectOne' accepting a first argument of of type 'object' could be found
我把HexagonControl
公开,但这并没有解决它。我还尝试创建一个object
并将sender
值传入,但这仍然没有解决它,它只是给了我这个Cannot implicitly convert type 'object' to 'LongName.HexagonControl'. An explicit conversion exists
可能导致此错误的原因是什么,以及如何解决它。
您必须将
sender
强制转换为HexagonControl
类型或将其值发送到另一个HexaControl
类型变量。请尝试以下操作:
void hexagon_Click(object sender, ActionEventArgs e)
{
if(sender.GetType() != typeof(HexagonControl))
return;
count++;
HexagonControl realSender = (HexagonControl) sender;
[...]
并在方法的其余部分使用 realSender
而不是 sender
。这样,您可以防止Exception
以防万一sender
不是HexagonControl
,只是为了预防。
希望对您有所帮助!
只需将sender
转换为其原始类型:
((HexagonControl)sender).RectOne.Fill = ((HexagonControl)sender).Brush;
当然,您还必须为其他 8 种用法执行此操作