Func vs string [英] Func vs string

查看:75
本文介绍了Func vs string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨伙计们,



假设我有以下代码工作流程:



Hi folks,

lets assume I have the following code workflow:

string s = "SOME_LONG_AND_NASTY_STRING_PROBABLY_A_BASE64_STRING";
WriteToDB(s);

public void WriteToDB(string str){
    InsertInDB(str);
}

public void InsertInDB(string str)
{
    //Do writing here using str
}





由于字符串值类型不可变使用它作为参数的方法调用将导致该字符串在内存中的副本。即使WriteToDB只是将字符串路由到InsertInDB,也会创建一个副本。为了最大限度地减少这种不良影响,我可以将其包装在一些数据容器中并传递容器。容器当然是引用类型。



如果我将字符串包装在Func< string>中怎么办?代表(见下文)?





Since the string is a value type immutable each method call with it as parameter leads to a copy of that string in the memory. Even if WriteToDB justs routes the string to InsertInDB a copy is created. To minimize this bad effect I can wrap it in some data container and pass the container around. The container is of course a reference type.

What if I wrap the string in a Func<string> delegate (see below)?

string s = "SOME_LONG_AND_NASTY_STRING_PROBABLY_A_BASE64_STRING";
WriteToDB(()=>s);

public void WriteToDB(Func<string> f_str){
    InsertInDB(f_str);
}

public void InsertInDB(Func<string> f_str)
{
    //Do writing here using f_str()
}





字符串是否包含在Func对象中并因此作为引用类型传递,就像我放置一样它在数据容器中?



我想阻止自己写一个数据容器来保存字符串。有没有更好的方法将字符串作为参数传递但没有一直复制?我知道ref关键字,但在这种情况下似乎也错了。



感谢您的建议。



Jens



Is it true that the string is wrapped inside the Func-object and therefore passed as a reference type just like if i put it in a data container?

Id like to prevent myself to write a data container just to hold the string. Is there a better way to have a string passed as a parameter but without having it copied all the time? I know the ref keyword, but that seems to be wrong either in this case.

Thanks for your suggestions.

Jens

推荐答案

因为字符串是什么时候是值类型?

相信我,所有.NET字符串都是引用类型,所以你的关注是无关紧要的。 (你的问题是:笑:):
Since when was a string a value type?
Trust me on this, all .NET strings are reference types, so your concern is immaterial. (As is your question :laugh:)


这篇关于Func vs string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆