Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Net中的字符串初始化_C#_.net_String - Fatal编程技术网

C# Net中的字符串初始化

C# Net中的字符串初始化,c#,.net,string,C#,.net,String,我可能遗漏了一些东西,但据我所知,string和string都是别名,如so中所述,string只是一个对象 现在我不明白的是下面的代码如何初始化String的新对象 string s="Hello World" 我可以对常规对象执行此技巧吗?正如@KirkWoll所提到的,您可以使用隐式运算符 差不多 public class FOO { private string _foo; public static implicit operator FOO(string foo)

我可能遗漏了一些东西,但据我所知,string和string都是别名,如so中所述,string只是一个对象

现在我不明白的是下面的代码如何初始化String的新对象

string s="Hello World"

我可以对常规对象执行此技巧吗?

正如@KirkWoll所提到的,您可以使用隐式运算符

差不多

public class FOO
{
    private string _foo;

    public static implicit operator FOO(string foo)
    {
        FOO f = new FOO {_foo = foo};
        return f;
    }
}
然后叫它

FOO bar = "TADA";

如果您正在代码中编译它们。。它们是编译时常量。。i、 代码从编译的二进制文件中显式引用它们,当然在运行时会加载到内存中

如果您在运行时构造它们。。和char数组一样,我猜CLR也有这样做的必要实现。例如,查看下面的代码

[System.Security.SecuritySafeCritical]//自动生成
私有静态字符串ConcatArray(字符串[]值,整数总长度){
字符串结果=FastAllocateString(总长度);
int currPos=0;

对于(int i=0;当您输入“字符串初始化C#”时,我从google获得了第一个链接)是的。这篇文章非常正式地解释了字符串是如何初始化的。是的,您可以将用户类型转换运算符从
字符串
重载到您的类型:每个字符串文本不一定会产生一个新的字符串实例。Troll注释:您的代码没有编译。它缺少一个
。很抱歉,我帮不上忙。@KirkWoll-我想这就是问题所在,也就是说,有没有一种方法可以为任意类型创建自定义文字初始值设定项。对于ldstr,尼斯+1!
[System.Security.SecuritySafeCritical]  // auto-generated
private static String ConcatArray(String[] values, int totalLength) {
    String result =  FastAllocateString(totalLength);
    int currPos=0;

    for (int i=0; i<values.Length; i++) {
        Contract.Assert((currPos <= totalLength - values[i].Length), 
            "[String.ConcatArray](currPos <= totalLength - values[i].Length)");

        FillStringChecked(result, currPos, values[i]);
        currPos+=values[i].Length;
    }

    return result;
}

[System.Security.SecurityCritical]  // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static String FastAllocateString(int length);