2

我在将这个小类从 Python 转换为 C# 时遇到了一些麻烦,有人可以帮我吗?

到目前为止,我有这个:

public class objDict
{
    public objDict(Dictionary<object, object> obj)
    {
        foreach(KeyValuePair<object, object> kvp in obj)
        {

        }
    }
}

剩下的我不知道该怎么做。我对 Python 只知道一点点
这是课程:

class objDict(object):

    def __init__(self, obj):
        for k, v in obj.iteritems():
            if isinstance(v, dict):
                setattr(self, _to_str(k).title(), objDict(v))
            else:
                setattr(self, k, v)

    def __getitem__(self, val):
        return self.__dict__[val]

    def __repr__(self):
        return '{%s}' % str(', '.join('%s : %s' % (k, repr(v)) for (k, v) in self.__dict__.iteritems()))

提前致谢!

4

2 回答 2

2

它应该是这样的:

class objDict : Dictionary<object, object>
{
    // __init__
    public objDict(IDictionary obj = null)
    {
        if (obj == null)
        {
            return;
        }

        foreach (DictionaryEntry kv in obj)
        {
            if (kv.Value is IDictionary)
            {
                // Not sure if it should be CultureInfo.InvariantCulture or CultureInfo.CurrentCulture
                this.Add(CultureInfo.InvariantCulture.TextInfo.ToTitleCase(kv.Key.ToString()), new objDict((IDictionary)kv.Value));
            }
            else
            {
                this.Add(kv.Key, kv.Value);
            }
        }
    }

    // __getitem__
    public object this[object key]
    {
        get
        {
            return this[key];
        }
    }

    // __repr__
    public string ToString()
    {
        return string.Join(", ", this.Select(p => string.Format("{0} : {0}", p.Key, p.Value)));
    }
}

我会说,Dictionary<object, object>如果我们排除内部字典将是浅克隆的并且有一个有用的.ToString().

于 2013-08-30T13:11:36.723 回答
0

有一个免费的在线工具可以自动将 Python 转换为 C#。结果并不完美,但消除了移植流控制等的许多痛苦。

https://pythoncsharp.com

namespace Namespace {
    
    using System;
    
    public static class Module {
        
        public class objDict
            : object {
            
            public objDict(object obj) {
                foreach (var _tup_1 in obj) {
                    var k = _tup_1.Item1;
                    var v = _tup_1.Item2;
                    if (v is dict) {
                        setattr(this, _to_str(k).title(), objDict(v));
                    } else {
                        setattr(this, k, v);
                    }
                }
            }
            
            public virtual object @__getitem__(object val) {
                return this.@__dict__[val];
            }
            
            public virtual object @__repr__() {
                return String.Format("{%s}", ", ".join(from _tup_1 in this.@__dict__.Chop((k,v) => (k, v))
                    let k = _tup_1.Item1
                    let v = _tup_1.Item2
                    select String.Format("%s : %s", k, repr(v))).ToString());
            }
        }
    }
}
于 2020-09-07T16:09:59.120 回答