c# - 在 C# 项目的另一个类中使用受保护的覆盖 void 中的变量
问题描述
通常我使用属性来使用类中另一个类的变量。然后它看起来像以下代码,其中服务器作为示例:
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”的公共类中有一个受保护的覆盖无效。
它看起来如下:
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;
}
}
推荐阅读
- cassandra - KairosDB H2 与 Cassandra
- javascript - Node js:当我从快速路由调用异步函数时,为什么会出现```TypeError: Cannot read property 'json' of undefined```?
- powershell - Azure Datalake Gen1 到 Azure 分析服务的服务到服务身份验证失败
- javascript - 单元测试角度ngrx组件
- wordpress - FPDF 图片不工作 - wordpress 插件
- javascript - 如何在 Cypress 中使用安全限制处理登录
- networking - 新的 Lamp Stack 部署网络接口不起作用
- amazon-s3 - 从 S3 复制数据时尝试映射列出现错误 SQL 编译错误:在“s3:bucket/file.csv.gz”中找到无效的 URL 前缀
- powershell - Powershell上的7zip命令无法解析?
- javascript - 如何在 react-native 中使用 i18n-js 将组件渲染为参数?