在 C# 中将字符串与属性相关联 [英] Relating strings to Properties in C#

查看:55
本文介绍了在 C# 中将字符串与属性相关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一堂课:

class Thing
{
    public string Id { get; set; }
    public string Foo { get; set; }
    public string Bar { get; set; }
}

而且我有一种 URL 参数样式约定,我希望允许使用以下字符串格式指定此类的值:

And I have a sort of URL parameter style convention, where I want to allow the specification of values for this class in the following string format:

"{Id}~foo={foo}~bar={bar}"

我可能想写一个类来做这样的事情:

I might want to write a class that does something like this:

class ThingHandler
{
    private static readonly IDictionary<string, (Func<Thing, string> GetValue, Action<Thing, string> SetValue)> dictionary =
        new Dictionary<string, (Func<Thing, string> GetValue, Action<Thing, string> SetValue)>
        {
            { "foo=", (new Func<Thing, string>((thing) => thing.Foo), new Action<Thing, string>((thing, value) => thing.Foo = value)) },
            { "bar=", (new Func<Thing, string>((thing) => thing.Bar), new Action<Thing, string>((thing, value) => thing.Bar = value)) },
        };

    public Thing Unstringify(string str)
    {
        Thing thing = new Thing();

        var split = str.Split('~');

        thing.Id = split.First();

        foreach (var keyValuePair in split.Skip(1))
        {
            var key = keyValuePair.Substring(0, 4);
            var value = keyValuePair.Substring(4);
            dictionary[key].SetValue(thing, value);
        }

        return thing;
    }

    public string Stringify(Thing thing)
    {
        StringBuilder stringBuilder = new StringBuilder(thing.Id);

        foreach (var item in dictionary)
        {
            var value = item.Value.GetValue(thing);
            if (!string.IsNullOrEmpty(value))
            {
                stringBuilder.Append(item.Key);
                stringBuilder.Append(value);
            }
        }

        return stringBuilder.ToString();
    }
}

像这样必须以两种不同的方式指定一个属性似乎很不雅,我们最终在这两个字典条目中产生了很多重复的代码.反射可以用来使这不那么混乱吗?但同样,我觉得它不应该是我的.像这样:

It just seems very inelegant to have to specify a property in two different ways like this, and we end up with a lot of repeated code in those two dictionary entries. Reflection could be used to make this less messy possibly? But again, it feels like it shouldn't have to be to me. Something like this:

{ "foo=", Property<Thing>((thing) => thing.Foo) },
{ "bar=", Property<Thing>((thing) => thing.Bar) },

会更整洁.我可以对在这种情况下可能有帮助的属性(远离反射)做些什么?

would be so much neater. Is there anything I can do with attributes (staying away from reflection) that might help in this instance?

此外,我是不是完全错了?有没有一种方法可以让处理字符串和属性之间的连接真正简洁明了?目前,我似乎经常需要将字符串与这样的属性相关联(或传递指向属性本身的指针),任何建议都将不胜感激.

Additionally, am I coming at this completely wrong? Is there a way of turning it on its head that makes handling the connection between a string and a property really succinct and neat? I seem to be encountering the need to relate strings to properties like this reasonably often at the moment, (or pass around a pointer to the property itself) and any advice would be much appreciated.

推荐答案

这个问题是 OP 试图在这里澄清他的原始问题:有没有办法存储指向 C# 中属性的指针?

This question is the OP's attempt to clarify his original question here: Is there a way to store a pointer to a property in C#?

OP 最初说他需要定期执行此操作,这表明他可能错误地处理了问题.看他上面的新问题,好像是序列化问题.

The OP originally said that he is running into a need to do this quite regularly, which suggests he may be approaching the problem incorrectly. Looking at his new question above, it appears to be a serialization problem.

OP 应该尽可能阅读有关序列化的所有内容,然后看看他是否可以组合出现成的解决方案.其他响应者建议使用 Newtonsoft JSON,我也认为这可能是 OP 的合适解决方案.众所周知,Newtonsoft 速度极快,几乎可以在任何情况下使用.它也非常健壮.

OP should go read everything he can about serialization and then see if he can put together an off the shelf solution. Other responders have suggested use of Newtonsoft JSON, which I also think may be an appropriate solution for the OP. Newtonsoft is known to be extremely fast, which makes it work on almost any situation. It's also pretty robust.

我建议不要使用 Json 序列化的唯一原因是 OP 是否需要他自己的更易读的格式.即使这是他的需要,仍有一些现成的方法可以实现这一目标.同样,OP 应该在继续之前阅读关于序列化的所有内容.

The only reason I would suggest NOT using Json serialization is if the OP needs his own more human-readable format. And even if that's his need, there are still some off-the-shelf ways of achieving that. Again, OP should read everything he can about serialization before proceeding.

这篇关于在 C# 中将字符串与属性相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆