class
C# では、参照型 (つまり、 の代わりに で宣言された型) を参照するものがある場合、struct
基本的に常にポインターを介してオブジェクトを処理しています。C++ ではすべてがデフォルトで値型ですが、C# ではすべてがデフォルトで参照型です。
C# のパラメーター リストで "ref" と言うとき、実際に言っているのは "ポインターへのポインター" のようなものです。メソッドでは、メソッドを呼び出すコードで、オブジェクトの内容ではなく、オブジェクト自体への参照を置き換えたいと言っています。
それがあなたの意図でない限り、参照型を直接渡す必要があります。C# では、参照型を渡すのは安価です (C++ で参照を渡すのと同じです)。
C# の値型と参照型の違いを学習/理解します。それらはその言語の主要な概念であり、C# の世界で C++ オブジェクト モデルを使用して考えようとすると、物事は非常に混乱するでしょう。
以下は、本質的に意味的に同等のプログラムです。
#include <iostream>
class AClass
{
int anInteger;
public:
AClass(int integer)
: anInteger(integer)
{ }
int GetInteger() const
{
return anInteger;
}
void SetInteger(int toSet)
{
anInteger = toSet;
}
};
struct StaticFunctions
{
// C# doesn't have free functions, so I'll do similar in C++
// Note that in real code you'd use a free function for this.
static void FunctionTakingAReference(AClass *item)
{
item->SetInteger(4);
}
static void FunctionTakingAReferenceToAReference(AClass **item)
{
*item = new AClass(1729);
}
};
int main()
{
AClass* instanceOne = new AClass(6);
StaticFunctions::FunctionTakingAReference(instanceOne);
std::cout << instanceOne->GetInteger() << "\n";
AClass* instanceTwo;
StaticFunctions::FunctionTakingAReferenceToAReference(&instanceTwo);
// Note that operator& behaves similar to the C# keyword "ref" at the call site.
std::cout << instanceTwo->GetInteger() << "\n";
// (Of course in real C++ you're using std::shared_ptr and std::unique_ptr instead,
// right? :) )
delete instanceOne;
delete instanceTwo;
}
C# の場合:
using System;
internal class AClass
{
public AClass(int integer)
: Integer(integer)
{ }
int Integer { get; set; }
}
internal static class StaticFunctions
{
public static void FunctionTakingAReference(AClass item)
{
item.Integer = 4;
}
public static void FunctionTakingAReferenceToAReference(ref AClass item)
{
item = new AClass(1729);
}
}
public static class Program
{
public static void main()
{
AClass instanceOne = new AClass(6);
StaticFunctions.FunctionTakingAReference(instanceOne);
Console.WriteLine(instanceOne.Integer);
AClass instanceTwo = new AClass(1234); // C# forces me to assign this before
// it can be passed. Use "out" instead of
// "ref" and that requirement goes away.
StaticFunctions.FunctionTakingAReferenceToAReference(ref instanceTwo);
Console.WriteLine(instanceTwo.Integer);
}
}