[英]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.