问题描述
通常,我使用属性来使用一个类中另一个类的变量。 然后,它看起来像以下代码,以以下服务器为例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Employee
{
private int _EmpID = 1001;
private string _EmpName;
public int EmpID
{
get
{
return _EmpID;
}
}
public string EmpName
{
get
{
return _EmpName;
}
set
{
_EmpName = "Smith";
}
}
}
class AcessEmployee
{
static void Main()
{
Employee objEmployee = new Employee();
Console.WriteLine("Employee ID: " + objEmployee.EmpID);
Console.WriteLine("Employee old Name: " + objEmployee.EmpName);
objEmployee.EmpName = "Dyne Smith";
Console.WriteLine("Employee New Name: " + objEmployee.EmpName);
Console.ReadLine();
}
}
}
现在,在名为“ DragCanvas_:Canvas”的公共类中,我有一个受保护的重写void。
它看起来如下:
public class DragCanvas_ : Canvas
{
protected override void OnPreviewMouseUp(MouseButtonEventArgs e)
{
base.OnPreviewMouseUp(e);
var positionTransform = this.ElementBeingDragged.TransformToAncestor(this);
var areaPosition = positionTransform.Transform(new Point(0,0));
// Reset the field whether the left or right mouse button was
// released,in case a context menu was opened on the drag element.
this.ElementBeingDragged = null;
var _left = areaPosition.X;
var _top = areaPosition.Y;
Console.WriteLine(areaPosition.X);
Console.WriteLine(areaPosition.Y);
}
}
我想在C#项目的另一个类中使用两个变量“ _left”和“ _top”。通用属性方法(请参见代码1)似乎不适用于“受保护的覆盖无效对象”。
解决方法
您仅声明了局部变量。您不能在覆盖功能之外使用它们。
var _left = areaPosition.X;
var _top = areaPosition.Y;
您应该使用public
修饰符将它们提升到班级,以使其在其他班级可以访问。
public class DragCanvas_ : Canvas
{
public double Left {get; set;}
public double Top {get; set;}
protected override void OnPreviewMouseUp(MouseButtonEventArgs e)
{
.....
Left = areaPosition.X;
Top = areaPosition.Y;
}
}
,
首先,您可以在属性中使用“语法糖”,以避免在代码中创建不必要的变量。 C#足够聪明,它本身会生成一个将访问的局部变量。
也就是说,而不是:
private int _EmpID = 1001;
public int EmpID
{
get
{
return _EmpID;
}
}
结果是一行
public int EmpId { get; private set; } = 1001;
第二,阅读更多有关变量可见性的信息。在方法的嵌套代码块中创建对象时,该对象仅在方法的该代码块中可见。
如果要在方法外使用变量,则有两种解决方案:
- 将变量声明为类的公共字段
public class DragCanvas_ : Canvas
{
public decimal Left { get; set; } //I don't know exactly what type of areaPosition.X
public decimal Right {get; set; }
protected override void OnPreviewMouseUp(MouseButtonEventArgs e)
{
... // your code in this method
Left = areaPosition.X;
Top = areaPosition.Y;
}
}
- 使用修饰符
out
从方法返回值。现在,您无需在类中声明变量。如果您不详细介绍,那么变量将在调用方法的阶段创建并立即作为参数传递
protected override void OnPreviewMouseUp(MouseButtonEventArgs e,out decimal Left,out decimal Top)
{
... // your code in this method
Left = areaPosition.X;
Top = areaPosition.Y;
}
在这种情况下,除非您以编程方式在代码中调用该方法,否则它对第二种选择无济于事。因此,这是为了提高您的知识。