Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.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#对象的大小_C# - Fatal编程技术网

如何确定C#对象的大小

如何确定C#对象的大小,c#,C#,我将我的对象定义如下: public class A { public object Result { get { return result; } set { result = value; } } } 然后我将一些字符串值存储在其中,如下所示: A.Result=stringArray; 这里stringArray有5个字

我将我的对象定义如下:

public class A
{
    public object Result
    {
        get
        {
            return result;
        }
        set
        {
            result = value;
        }
    }
}
然后我将一些字符串值存储在其中,如下所示:

A.Result=stringArray;
这里stringArray有5个字符串值。
现在我想在其他地方使用这个对象,并且想知道这个对象中字符串值的长度。如何计算?

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

例如:

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;
}

如果只是查找
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;
}

哪个字符串值?您是指“stringArray”的长度吗?或此数组中每个字符串的值?是否尝试强制转换为
字符串[]
?实际上,我想知道.Result中存储了多少字符串值?
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;
}