使用带有属性的静态方法

时间:2014-03-20 11:45:15

标签: c# methods properties static

我几天前发现了一些属性(不确定我是否理解如何使用它们)。所以我决定做一些测试。 所以这就是我所做的: 我创建了一个包含一些属性的类,如:

public string _string1 { get; set; }
public string _string2 { get; set; } 

然后我在同一个类中创建了一个方法,让我们这样说:

public static string  Example()
{
   switch(_string1.length > _string2.length)
   {
      case true :
             return _string1;
             break;
      default : return _string2;
   }
}

只是一个愚蠢的例子来理解一点 然后我从主类调用了方法,之后我遇到了一些错误: 非静态字段,方法或属性'xxx.properties._string1.get'

需要对象引用

那肯定是一个愚蠢的错误,但我是c#的新手,我可以使用一些帮助。

4 个答案:

答案 0 :(得分:10)

您还需要使属性保持静态:

public static string _string1 { get; set; }
public static string _string2 { get; set; } 

基本上静态方法没有状态。以非静态方式声明的那些字段基本上类似于状态,因此它无法访问它们。通过将它们标记为静态,您可以说这是AppDomain的全局值。

要谨慎使用像这样的静态字段,但是如果你开始使用任何类型的线程并尝试存储状态,那么你最终可能会遇到令人讨厌的问题进行调试,因为你不知道你的状态是什么共享资源在。

防止这种情况(如果你不需要状态)的方法是将它们定义为常量字段。然后你不能修改它们,但意味着你不必担心有人在你没想到的时候改变它们。

public const string _string1;
public const string _string2;

答案 1 :(得分:1)

静态方法始终只能访问其他静态成员。现在,由于您的属性不是静态的,因此静态方法无法访问/操作它们。

您可以将这些字段设为静态,然后错误就会消失。一旦这些是静态的,就不需要对象引用来访问它们。 然后可以通过类名本身简单地访问它们。

例如

public class YourClass
{
  public static string _string1 { get; set; }
  public static string _string2 { get; set; } 

  public static string  Example()
  {
    switch(_string1.length > _string2.length)
    {
     case true :
         return _string1;
         break;
     default : return _string2;
    }
  }
}

现在在您的计划中:

YourClass._string1="some string";  // You can access the static properties with class name
YourClass._string2="some other string";

YourClass.Example() // You can call the static function with class name.

答案 2 :(得分:1)

所有关于实例与静态范围的关系。虽然上面的示例使您的错误消失,但了解何时使用静态方法,变量,属性与实例相比非常重要。事实上,你可以说使用静态成员并不是一个纯粹的OOP实践。大多数情况下,静态成员被滥用,因为人们误解了这些OOP基础知识。

静态方法和变量在您的类的所有对象实例之间共享。因此,在大多数情况下,您需要具有静态方法/变量的特定要求,例如将对象的总计数保留在可在所有对象实例中访问的静态变量中。

答案 3 :(得分:0)

您可以在其中创建变量的类的新实例。

public class YourClass
{
   public string _string1 { get; set; }
   public string _string2 { get; set; } 
   ...
}

public static string  Example()
{
   YourClass yourClass = new YourClass();
   switch(_string1.length > _string2.length)
   {
      case true :
             return yourClass._string1;
             break;
      default : return yourClass._string2;
   }
}