首页 > 解决方案 > 在 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)似乎不适用于“受保护的覆盖无效”。

标签: c#wpfvariablesdrag

解决方案


您只声明了局部变量。您不能在被覆盖的函数之外使用它们。

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;
  }
}

推荐阅读