【问题标题】:error CS0120: An object reference is required for the non-static field, method, or property 'Encoding.GetBytes(string)' [duplicate]错误 CS0120:非静态字段、方法或属性“Encoding.GetBytes(string)”需要对象引用 [重复]
【发布时间】:2023-03-13 09:37:01
【问题描述】:
我正在使用 .NET 制作控制台应用程序,当我运行程序时出现此错误。
error CS0120: An object reference is required for the non-static field, method, or property Encoding.GetBytes(string)。
它说错误来自这一行:
content.Add(Encoding.GetBytes("\n"+str));(content是string类型的List,str是string)
【问题讨论】:
标签:
c#
.net
console
runtime-error
【解决方案1】:
在Encoding.GetBytes Method 文档中:
public virtual byte[] GetBytes(char[] chars);
它不是静态方法,因此不能直接调用Encoding.GetBytes方法。
相反,您需要声明并分配一个Encoding 变量;然后才使用这个变量调用GetBytes方法。
var str = "Happy ending"; // Sample data
var encoding = Encoding.UTF8; // Set to your desired encoding
var bytes = encoding.GetBytes("\n"+str); // Return type: byte[]
要将bytes 添加到List 的内容中,您可以先将bytes 转换为所需的格式。
[不是.ToString(),它会返回结果:“System.Byte[]”]
var byteString = String.Join(" ", bytes); // Format to your desired format
// Result of byteString: 10 72 97 112 112 121 32 101 110 100 105 110 103
content.Add(byteString);