简体   繁体   English

C#获取/设置语法用法

[英]C# Get/Set Syntax Usage

These are declarations for a Person class. 这些是Person类的声明。

protected int ID { get; set; }
protected string Title { get; set; }
protected string Description { get; set; }
protected TimeSpan jobLength { get; set; }

How do I go about using the get/set? 我如何使用get / set? In main, I instantiate a 主要是,我实例化了一个

Person Tom = new Person();

How does Tom.set/get?? Tom.set / get怎么样?

I am use to doing C++ style where you just write out the int getAge() and void setAge() functions. 我习惯于做C ++风格,你只需写出int getAge()和void setAge()函数。 But in C# there are shortcuts handling get and set? 但是在C#中有快捷方式处理get和set?

Assuming you have access to them (the properties you've declared are protected ), you use them like this: 假设您有权访问它们(您声明的属性protected ),您可以像这样使用它们:

Person tom = new Person();
tom.Title = "A title";
string hisTitle = tom.Title;

These are properties . 这些是属性 They're basically pairs of getter/setter methods (although you can have just a getter, or just a setter) with appropriate metadata. 它们基本上是一对getter / setter方法(虽然你可以只有一个getter,或者只是一个setter),并带有适当的元数据。 The example you've given is of automatically implemented properties where the compiler is adding a backing field. 您给出的示例是自动实现的属性 ,其中编译器正在添加支持字段。 You can write the code yourself though. 您可以自己编写代码。 For example, the Title property you've declared is like this: 例如,您声明的Title属性是这样的:

private string title; // Backing field
protected string Title
{
    get { return title; }  // Getter
    set { title = value; } // Setter
}

... except that the backing field is given an "unspeakable name" - one you can't refer to in your C# code. ...除了支持字段被赋予“无法形容的名称” - 您无法在C#代码中引用。 You're forced to go through the property itself. 你被迫通过房产。

You can make one part of a property more restricted than another. 您可以使财产的一部分比另一部分更受限制。 For example, this is quite common: 例如,这很常见:

private string foo;
public string Foo
{
    get { return foo; }
    private set { foo = value; }
}

or as an automatically implemented property: 或作为自动实施的财产:

public string Foo { get; private set; }

Here the "getter" is public but the "setter" is private. 这里的“getter”是公开的,但“setter”是私有的。

Assuming you have a song class (you can refer below), the traditional implementation would be like as follows 假设你有一个歌曲类(你可以参考下面),传统的实现方式如下

 class Song
  {
       private String author_name;
       public String setauthorname(String X) {}; //implementation goes here
       public String getauthorname() {}; //implementation goes here
  }

Now, consider this class implementation. 现在,考虑这个类的实现。

      class Song 
      {
            private String author_name;
            public String Author_Name
            { 
                 get { return author_name; }
                set { author_name= value; }
             }
      }

In your 'Main' class, you will wrote your code as 在“Main”课程中,您将编写代码为

    class TestSong
    { 
      public static void Main(String[] Args)
      {
          Song _song = new Song(); //create an object for class 'Song'    
          _song.Author_Name = 'John Biley';
          String author = _song.Author_Name;           
          Console.WriteLine("Authorname = {0}"+author);
      }
    }

Point to be noted; 需要注意的一点;

The method you set/get should be public or protected(take care) but strictly shouldnt be private. 您设置/获取的方法应该是公开的或受保护的(小心),但严格来说不应该是私有的。

These are properties . 这些是属性 You would use them like so: 您会像这样使用它们:

Tom.Title = "Accountant";
string desc = Tom.Description;

But considering they are declared protected their visibility may be a concern. 但考虑到他们被宣布protected他们的知名度可能是一个问题。

By the way, in C# 3.5 you can instantiate your object's properties like so: 顺便说一句,在C#3.5中,您可以实例化对象的属性,如下所示:

Person TOM=new Person 
{ 
   title = "My title", ID = 1 
};

But again, properties must be public. 但同样,财产必须是公开的。

I do not understand what this is unclear 我不明白这是不清楚的

Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. 属性是提供灵活机制来读取,写入或计算私有字段值的成员。 Properties can be used as though they are public data members, but they are actually special methods called accessors. 可以使用属性,就像它们是公共数据成员一样,但它们实际上是称为访问器的特殊方法。 This enables data to be accessed easily while still providing the safety and flexibility of methods. 这使得数据易于访问,同时仍然提供方法的安全性和灵活性。

In this example, the class TimePeriod stores a time period. 在此示例中,类TimePeriod存储时间段。 Internally the class stores the time in seconds, but a property called Hours is provided that allows a client to specify a time in hours. 在内部,类以秒为单位存储时间,但提供了一个名为Hours的属性,允许客户端指定以小时为单位的时间。 The accessors for the Hours property perform the conversion between hours and seconds. Hours属性的访问器执行小时和秒之间的转换。

Example

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}

class Program
{
    static void Main()
    {
        TimePeriod t = new TimePeriod();

        // Assigning the Hours property causes the 'set' accessor to be called.
        t.Hours = 24;

        // Evaluating the Hours property causes the 'get' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);
    }
}

Properties Overview 属性概述

Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. 属性使类能够公开获取和设置值的公共方式,同时隐藏实现或验证代码。

A get property accessor is used to return the property value, and a set accessor is used to assign a new value. get属性访问器用于返回属性值, set访问器用于分配新值。 These accessors can have different access levels. 这些访问者可以具有不同的访问级别。

The value keyword is used to define the value being assigned by the set indexer. value关键字用于定义set indexer分配的值。

Properties that do not implement a set method are read only. 不实现set方法的属性是只读的。

http://msdn.microsoft.com/en-US/library/x9fsa0sw%28v=vs.80%29.aspx http://msdn.microsoft.com/en-US/library/x9fsa0sw%28v=vs.80%29.aspx

Set them to public. 将它们设置为公开。 That is, wherever you have the word "protected", change it for the word "public". 也就是说,只要你有“受保护”这个词,就改为“公共”这个词。 If you need access control, put it inside, in front of the word 'get' or the word 'set'. 如果您需要访问控制,请将其放在“get”或“set”一词的前面。

You are not able to access those properties as they are marked as protected meaning: 您无法访问这些属性,因为它们被标记为protected含义:

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class. 类型或成员只能由同一个类或结构中的代码访问,或者在从该类派生的类中访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM