[英]Ruby, variables and their C# equivalent
我試圖繞過Ruby變量,並認為用C#來看它們可能會很好
有人能告訴我C#等價的Ruby(例如@@ == public static variable?):
$ global變量
@ instance變量
@@類變量
[az]局部變量
[AZ]不變
我遺失的任何其他類型的變量?
有人還可以解釋@instance變量是如何使用/函數的嗎?
起初我認為它是類的實例中的一些全局變量,但后來我看到它在實例的方法中使用了像局部變量這樣的范圍。
這是'好地基的紅寶石'的一個例子
class C
def show_var
@v = "i am an instance variable initialized to a string"
puts @v
end
@v = "instance variables can appear anywhere..."
end
C.new.show_var
如果我想讓'v'成為類實例中任何位置的相同變量,那么執行此操作的Ruby機制是什么?
C#不使用sigils作為變量。
“等效”C#變量完全取決於變量/成員的定義方式 。 請注意,“等效”形式之間甚至存在差異。
但是,鼓勵遵循許多命名約定 。 使用的確切約定因項目而異,可能與我在下面選擇的名稱不同,這反映了我的慣例 - 不要在實際變量名中使用“class”或“instance”或“local”。
例子:
class MyClass: IMyInterface {
// "const" makes it constant, not the name
public const int CONSTANT = 42;
// static member variable - somewhat like Ruby's @@variable
private static int classVariable;
public static int ExposedClassVariable; // but use properties
// @variable - unlike Ruby, can be accessed outside "self" scope
int instanceVariable;
public int ExposedInstanceVariable; // but use properties
void method (int parameter) {
int localVariable;
}
}
C#沒有“共享命名空間中的全局變量”,但靜態成員變量可以通過穩定路徑訪問,這意味着它們可以被有效地濫用為全局變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.