【问题标题】:Get public variable from another class从另一个类获取公共变量
【发布时间】:2018-04-27 17:38:35
【问题描述】:

我有一个类,其中有一个我想从另一个类访问的公共静态变量。这是课程: 在 GlobalVariable.cs 中

public class GlobalVariable
{
    public static int MoisVS = 3;
}

我想从另一个班级访问“MoisVS”。这是课程: 在 ArretPage.cs 中

var globalvariable = new ProjetTN.Class.GlobalVariable();
globalvariable.MoisVS;  //<--- Make something like that.

我知道这在 WinForm 应用程序中是可能的,但在 Xamarin.forms 应用程序中是可能的吗?

【问题讨论】:

  • 你为什么不试试呢?
  • @MathiasR.Jessen 我试过了,但没有成功,这就是我问这个问题的原因:)

标签: c# variables xamarin.forms


【解决方案1】:

您将MoisVS 定义为静态,因此您无法从实例变量访问它。访问使用类名本身的类的静态成员。因此,例如访问您的 MoisVS 将如下所示:

GlobalVariable.MoisVS

如果您想将其作为实例属性访问,您必须将您的类更改为:

public class GlobalVariable
{
    public int MoisVS = 3;
}

如果您的类中只有静态或常量值。你也可以决定让你的整个班级都是静态的

public static class GlobalVariable
{
    public static int MoisVS = 3;
    public const string MyString = "";
}

这将阻止您使用 new 关键字来创建该类的实例。

【讨论】:

    【解决方案2】:

    我将把它分成几个步骤。

    1)文件->新建文件->常规->选择空类->命名(例如UICONTROL_NAMES)

    2) 添加以下内容:(示例代码)

    using System;
    
    namespace iOSControls.HelperClass
    {
        public static class UICONTROL_NAMES
        {
            public const string textField = "Text Fields";
            public const string inputTextField = "Input types - TextFields";
            public const string button = "Buttons";
            public const string label = "Label";
    }
    

    做笔记:

    UICONTROL_NAMES class is inside a folder group called HelperClass and iOSControls is the project name.
    

    3) 在您的 ViewController.cs 上,添加命名空间指令。

    using iOSControls.HelperClass;
    using Foundation;
    

    4) 访问 UICONTROL NAMES 中的 const 字符串:

    string controlName = UICONTROL_NAMES.textField;
    

    【讨论】:

      猜你喜欢
      • 2022-11-14
      • 2015-07-26
      • 2013-10-04
      • 1970-01-01
      • 2020-11-17
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      相关资源
      最近更新 更多