[英]c# how to use Property
我想了解有關c#的更多信息,並且聽說您應該使用Private說明符並使用get / set將其公開。
我有一個小應用程序,它可以接收文本框數據並將其寫入文件。 並且它加密文件。
但是我無法掌握有關獲取器和設置器的概念。 這是我寫文件的類和方法之一。
class MyClass
{
public static bool WriteToFile(string text)
{
string FileName = "C:\\crypt\\crypt.txt";
try
{
using (System.IO.StreamWriter WriteToFile = new System.IO.StreamWriter(FileName))
{
WriteToFile.Write(text);
WriteToFile.Close();
}
return true;
}
catch
{
return false;
}
}
但是我想使用一個屬性。 我該怎么辦?
這就是我從主類傳遞textbox-data的方式。
public void button1_Click(object sender, EventArgs e)
{
MyClass c = new MyClass();
if (MyClass.WriteToFile(textBox1.Text))
MessageBox.Show("success, managed to write to the file");
else
MessageBox.Show("Error, Could not write to file. Please check....");
我看過各種教程,例如https://channel9.msdn.com/series/C-Fundamentals-for-Absolute-Beginners/15和教程,但我真的很努力。
WriteToFile
是一種方法 。
方法是方法,屬性是屬性。
方法封裝行為,而屬性封裝state 。
WriteToFile
不應是屬性,因為它不會封裝狀態。 實際上,它嘗試寫入文件系統。
屬性的示例為:
public class MyClass
{
private bool _canWrite;
/// Checks whether the file can be written into the file system
public bool CanWrite
{
get { return _canWrite; }
}
}
在另一個類中,您可以這樣稱呼它:
if(myClass.CanWrite)
{
// ...
}
請注意, CanWrite
並未定義任何行為,它只是為_canWrite
字段定義了一個吸氣劑,這確保了外部類不會對您的類有太多了解。
還要注意,我僅定義了一個吸氣劑,這會阻止其他人設置您的屬性。
好的,所以我認為對於您而言,您不需要屬性,但是如果我們假設您不希望創建某種包裝類來處理所有對文件的寫入,則可以按照以下步驟進行操作
class AwesomeFileWriter
{
private const string FileName = "C:\\crypt\\crypt.txt";
private readonly string _text;
public AwesomeFileWriter(string text)
{
_text = text;
}
public bool WriteToFile()
{
try
{
using (System.IO.StreamWriter WriteToFile = new System.IO.StreamWriter(FileName))
{
WriteToFile.Write(_text);
WriteToFile.Close();
}
return true;
}
catch
{
return false;
}
}
}
除了一件小事情,您的設計沒有太多更改。 但首先要注意的是:
您可以將該代碼放入屬性中嗎? 當然。 你應該? 一點也不。 您的方法WriteToFile
實際上正在做某事。 那就是什么方法。 另一方面,屬性用於修改/存儲數據。
這就是為什么屬性名稱聽起來更像名稱,而方法名稱通常聽起來像命令的原因:
例
public class Sample
{
private string someText;
// This Property Stores or modifies SomeText
public string SomeText
{
get { return this.someText; }
set { this.someText = value; }
}
// Method that does sth. (writes sometext to a given File)
public void WriteSomeTextToFile(string File)
{
// ...
}
}
為什么選擇屬性/修飾符?
像上面的示例一樣,將數據封裝在屬性內被認為是一種好習慣。 小改進可能是使用AutoProperty,如下所示:
public string SomeText { get; set; }
基本上產生與第一個示例中的封裝字段組合相同的結構。
為什么? :,因為這樣可以很容易地將其切換出去或為您的獲取/設置操作添加邏輯。
例如,您可以添加驗證:
public string SomeText
{
// ...
set
{
if (value.Length > 100)
throw new Exception("The given text is to long!");
this.someText = value;
}
}
注意:可能會改善您的課程
我唯一想到的改進就是不要在您的write方法中吞下異常:
public void WriteToFile()
{
using (var fileWriter= new System.IO.StreamWriter(FileName))
{
fileWriter.Write(_text);
fileWriter.Close();
}
}
這更加干凈,您不必“決定”級聯來處理相同的問題(您的try
/ catch
和if
/ else
)實際上是在做相同的事情。
public void button1_Click(object sender, EventArgs e)
{
try
{
var c = new MyClass();
c.WriteToFile(textBox1.Text))
MessageBox.Show("success, managed to write to the file");
}
catch(Exception e)
{
MessageBox.Show("Error, Could not write to file. " + e.Message);
}
}
這樣,您不僅具有相同的行為,而且不僅擁有操作不成功的原始事實( false
),還擁有更多信息。
在沒有實際向您展示代碼的情況下,我將嘗試解釋獲取器和設置器,以便您了解其概念。
屬性看起來像是內部類的方法,而字段是外部類的字段。
例如,您可以在屬性中執行邏輯,而當您從其他類調用屬性時,其行為與任何其他字段一樣。
GET:用於檢索和返回屬性。 在實際返回屬性之前,您可以執行一些復雜的邏輯。 您可以通過Get安全地公開私有變量,而不會影響編寫。
SET:用於設置可以是私有,常量或公共屬性的值。 您可以控制變量的設置。
通常,屬性用於將值保留為屬性。 特性 設置。
您認為是行動的方法和功能。
例如如下所示:
public class MyClass{
/// <summary>
/// Keeps the file name
/// </summary>
public string FileName { get; set; }
/// <summary>
/// Action to write the file
/// </summary>
/// <returns>Returns true if the info. was wrote into the file.</returns>
public bool WriteToFileSucceed()
{
try
{
using (System.IO.StreamWriter WriteToFile = new System.IO.StreamWriter(FileName))
{
WriteToFile.Write(text);
WriteToFile.Close();
}
return true;
}
catch
{
return false;
}
}}
...
public void button1_Click(object sender, EventArgs e){
MyClass myClass = new MyClass();
myClass.FileName = @"C:\crypt\crypt.txt";
if(myClass.WriteToFileSucceed())
{
MessageBox.Show("Success, managed to write to the file");
}
else
{
MessageBox.Show("Ops! Unable to write to the file.");
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.