[英]How to determine size of the C# Object
我将对象定义如下:
public class A
{
public object Result
{
get
{
return result;
}
set
{
result = value;
}
}
}
然后我将一些字符串值存储在其中:
A.Result=stringArray;
这里的stringArray有5个字符串值。 现在我想在其他地方使用该对象,并且想知道该对象内部字符串值的长度。 怎么样?
var array = A.Result as string[];
if (array != null)
{
Console.WriteLine(array.Length);
}
如果您只是在寻找Result
的长度(如果它是一个字符串),则可以执行以下操作。
var s = Result as string;
return s == null ? 0 : s.Length;
根据您在输入所有内容时的评论。 听起来以下是您真正想要的
如果是数组:
var array = Result as string[];
return array == null ? 0 : array.Length;
或者,如果您想要数组中所有项目的总长度:
var array = Result as string[];
var totalLength = 0;
foreach(var s in array)
{
totalLength += s.Length;
}
如果您想知道字节大小,则需要知道编码。
var array = Result as string[];
var totalSize = 0;
foreach(var s in array)
{
//You'll need to know the proper encoding. By default C# strings are Unicode.
totalSize += Encoding.ASCII.GetBytes(s).Length;
}
您可以通过将对象转换为字符串数组来获取其长度。
例如:
static void Main(string[] args) {
A.Result = new string[] { "il","i","sam","sa","uo"}; //represent as stringArray
string[] array = A.Result as string[];
Console.WriteLine(array.Length);
Console.Read();
}
您的对象无效,所以我重写:
public class A
{
public static object Result { get; set; } //I change it to static so we can use A.Result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.