如何在c#中返回对字符串的引用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/296913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return a reference to a string in c#?
提问by Aaron Fischer
I am looking to write a function like
我想写一个像
ref String TestIt( int index )
{
return this.TestArray[index];
};
so that I could write code like:
这样我就可以编写如下代码:
MyClass.TestIt(0) = "Hello World";
My goal is to mimic this c++ declaration
我的目标是模仿这个 c++ 声明
CString& MyClass::Data( UINT index);
By Reference I am referring to the c++ term the Address of the variable.
in other words after my call to TestIT(0)
TestArray[0] would contain "Hello World".
通过引用,我指的是 C++ 术语变量的地址。
换句话说,在我调用 TestIT(0) TestArray[0] 之后将包含“Hello World”。
EDITI can't use an indexer because my goal is to convert a .cpp file to c# on an ongoing basis. The closer I can mimic this c++ code, the less of a converter I have to write.
编辑我不能使用索引器,因为我的目标是持续将 .cpp 文件转换为 c#。我越能模仿这个 C++ 代码,我必须编写的转换器就越少。
采纳答案by Konrad Rudolph
To do this you need to write a setter property. Unfortunately, setters can't take further arguments in C# so you won't be able to write this code 1:1 in C#. The closest you can get is a nested class with a default property:
为此,您需要编写一个 setter 属性。不幸的是,setter 不能在 C# 中接受更多参数,因此您将无法在 C# 中 1:1 编写此代码。您可以获得的最接近的是具有默认属性的嵌套类:
class YourClass {
public class Nested {
public Nested(YourClass outer) { m_RefToOuterWorld = outer; }
private readonly YourClass m_RefToOuterWorld;
public string this[int index] {
get { return m_RefToOuter.TestArray[index];
set { m_RefToOuter.TestArray[index] = value; }
}
}
private readonly Nested m_Nested;
private string[] TestArray = new string[10];
public YourClass() { m_Nested = new Nested(this); }
public Nested TestIt { get { return m_Nested; } }
}
You can use it like this:
你可以这样使用它:
var test = new YourClass();
test.TestIt[2] = "Hello world!";
By the way, since this is so much effort, you probably don't want to do this. Also, it doesn't feel very C#-y. The useless indiretion through the nested class here isn't something you'll see very often.
顺便说一下,由于这太费力了,您可能不想这样做。此外,它感觉不是很 C#-y。通过这里的嵌套类无用的 indiretion 不是你经常会看到的。
回答by Jeff Kotula
You don't need to return a reference to achieve your goal. String types are reference types but has special handling for comparisons. So if you just return a string from TestIt the equality check will do a string comparison.
您无需返回引用即可实现目标。字符串类型是引用类型,但有特殊的比较处理。因此,如果您只是从 TestIt 返回一个字符串,则相等性检查将进行字符串比较。
回答by Bjarke Ebert
The short answer is that you cannot return a reference to a string variable, i.e. a reference to the string reference).
简短的回答是您不能返回对字符串变量的引用,即对字符串引用的引用)。
The simple solution is to avoid this kind of API and require the user to set the string in another way:
简单的解决方案是避免这种 API 并要求用户以另一种方式设置字符串:
myobj.SetString(0, "Hello, world!");
If you reallyneed to represent (as a first-class object) a reference to your string reference, try something like this API:
如果您确实需要表示(作为一等对象)对您的字符串引用的引用,请尝试使用以下 API:
Interface IStringReference
{
void SetString(string value);
string GetString();
}
class MyClass
{
public IStringReference TestIt()
{
... details left out ;) ...
}
}
but I think this is going too far in mimicking C++'s lvalues.
但我认为这在模仿 C++ 的左值方面做得太过分了。
回答by Amy B
Wouldn't you just use an indexer (an anonymous property that takes parameters)?
你不会只使用索引器(一个带参数的匿名属性)吗?
private string []storage = new string[10];
public string this[int index]
{
get
{
return storage[index];
}
set
{
storage[index] = value;
}
}
and then called with:
然后调用:
MyClass[0] = "Hello World";
Sure, it doesn't have the fancy "TestIt" name tag... do you need that name tag?
当然,它没有花哨的“TestIt”名牌……你需要那个名牌吗?
Edit: Lol, I googled for "C# named indexers" and who did I find answering silly questions with excellent answers in 2005? None other than Jon Skeet.
编辑:大声笑,我在 google 上搜索了“C# 命名索引器”,我发现谁在 2005 年用出色的答案回答了愚蠢的问题?除了乔恩斯基特。
回答by MichaelT
I can recomend following sollution
我可以推荐以下解决方案
public class Test
{
Dictionary<int,string> str=new Dictionary<int,string>();
public string this[int i]
{
get
{
return str[i];
}
set
{
if(!str.ContainsKey(i))
str.Add(i,value);
else
str[i] = value;
}
}
回答by MichaelT
Why bother to keep 2 versions of the code identical? Wouldn't it be easier to write a managed C++ wrapper that you could just use from .Net and then call the appropriate functions?
为什么要保持两个版本的代码相同?编写一个可以从 .Net 使用的托管 C++ 包装器然后调用适当的函数不是更容易吗?
回答by Jason
All identical strings have only one reference, no matter how many times it is referenced in the code.
所有相同的字符串只有一个引用,无论它在代码中被引用多少次。
From http://msdn.microsoft.com/en-us/library/system.string.intern.aspx
来自http://msdn.microsoft.com/en-us/library/system.string.intern.aspx
The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.
For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable.
公共语言运行时通过维护一个称为内部池的表来保存字符串存储,该表包含对在程序中以编程方式声明或创建的每个唯一文字字符串的单个引用。因此,具有特定值的文字字符串的实例在系统中仅存在一次。
例如,如果您将相同的文字字符串分配给多个变量,则运行时将从实习池中检索对文字字符串的相同引用并将其分配给每个变量。