.net 如何从数组中获取值,并将其放入对象中?[关闭]

z8dt9xmd  于 2023-05-19  发布在  .NET
关注(0)|答案(2)|浏览(223)

已关闭,此问题需要details or clarity。目前不接受答复。
**想改善这个问题吗?**通过editing this post添加详细信息并澄清问题。

10天前关闭。
Improve this question
我正在做json解析器,所以我需要通用的方法,这就是为什么我不能int[] arr = obj as int[];

int[] array = new int[] { 0, 1, 2 };
 object obj = array;
//I need to get value from the 'obj'

我试着用反思的方法,但我的知识不足以解决问题。我也试着使用How to extract elements of an array in object type in c#?的解决方案,但它没有帮助我。
UPD
我正在得到随机对象,我必须将其转换成json格式ecma-404。但是我在转换数组时遇到了问题,因为我无法获取值。

private static string ReadObject(object obj) {
            string json = "{";
            TypedReference reference = __makeref(obj);
            foreach(var fromField in obj.GetType().GetFields()) {
                var toField = obj.GetType().GetField(
                    fromField.Name, BindingFlags.Public | BindingFlags.Instance);

                object value = fromField.GetValueDirect(reference);
                if(value == null)  json += toField.Name + ':' + "null" + ',';
                else json += toField.Name + ':' + WriteValue(value, value.GetType()) + ',';

            }
            json = json.Remove(json.Length - 1);
            json += '}';
            return json;
        }

 public static string SerializeArray(object obj) {
            string json = "[";
//here must be code
            return json;
        }
mqxuamgl

mqxuamgl1#

好吧,把它还原成原来的样子有什么不对?

int[] array = obj as int[];
cbjzeqam

cbjzeqam2#

这太简单了:

if(obj is Array arr) {
    foreach( var item in arr ) {
          Console.WriteLine(item);
    }
 }

相关问题