简体   繁体   English

如何在c#中复制只读对象并修改副本

[英]How to copy a readonly object in c# and modify the copy

I have an object defined as: 我有一个对象定义为:

readonly List<object> Params;

I need to get the values stored in the list as integers but all the casting methods I have tried like Convert class, explicit typecasting using (int) give the following error: 我需要将列表中存储的值作为整数获取,但我尝试过的所有类似Convert类,使用(int)显式类型转换的转换方法都会出现以下错误:

Unhandled Exception: System.InvalidCastException 未处理的异常:System.InvalidCastException

I tried to print the elements and it gives me the integer value of the objects but copying the list keeps the readonly attribute and I am unable to use the value in my program. 我试图打印元素,它给了我对象的整数值,但复制列表保持readonly属性,我无法使用我的程序中的值。

You could use Linq to do this, for sample, add this namespace 您可以使用Linq执行此操作,例如,添加此命名空间

using System.Linq;

And try to use the Cast<T> method to convert, 并尝试使用Cast<T>方法进行转换,

List<int> ints = Params.Cast<int>();

You also could use the Select method if you need to do something more specific, for sample: 如果您需要针对示例执行更具体的操作,也可以使用Select方法:

List<int> ints = Params.Select(x => {

                                     // its a scope, and you can do it here...

                                     if (something)
                                        return (int) x;
                                     else if (other condition)
                                        return int.Parse(x.ToString());

                                      return x; // other custom conversions...

                                    }).ToList();

If the elements in the list are strings, use 如果列表中的元素是字符串,请使用

int value = int.Parse((string)Params[i]);

If the elements int the list are ints, use 如果列表中的元素是int,请使用

int value = (int)Params[i];

The readonly has no effect at all on the values stored in the list. readonly对列表中存储的值完全没有影响。 It applies only to the List object, but not to its content. 它仅适用于List对象,但不适用于其内容。 So forget about it, nothing wrong here. 所以忘掉它,没有错。

Instead, there MUST be a conversion problem with at least one of the values stored in Params (btw.: the exception clearly says that)... 相反,必须存在一个转换问题,其中至少有一个值存储在Params (顺便说一句:例外清楚地说明了这一点)......

You may use int.TryParse(...) to find out which value it is. 您可以使用int.TryParse(...)来找出它是哪个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM