2014-11-21 105 views
0

我定义我的目标如下:如何确定C#对象的大小

public class A 
{ 
    public object Result 
    { 
     get 
     { 
      return result; 
     } 
     set 
     { 
      result = value; 
     } 
    } 
} 

和那我存储在它里面的一些字符串值:

A.Result=stringArray; 

这里字符串数组有5个字符串值。 现在我想在其他地方使用该对象,并想知道该对象内部的字符串值的长度。怎么样?

+1

哪个字符串值?你的意思是'stringArray'的长度?或者这个数组中的每个字符串的值? – Fedor 2014-11-21 05:56:06

+0

您是否尝试转换为'string []'? – IVAAAN123 2014-11-21 05:56:49

+0

其实我想知道有多少字符串值存储在A.Result中? – 2014-11-21 05:58:19

回答

1

如果你只是在寻找的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; 
} 
0

您可以通过将对象的长度转换为字符串数组来获得对象的长度。

例如:

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; 
} 
1
var array = A.Result as string[]; 

if (array != null) 
{ 
    Console.WriteLine(array.Length); 
}