.NET:是否有插入对象属性的值转换成字符串的String.Format形式? [英] .NET: Is there a String.Format form for inserting the value of an object property into a string?

查看:170
本文介绍了.NET:是否有插入对象属性的值转换成字符串的String.Format形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得直接回答的问题是'不',但我希望有人写了一个真正简单的库来做到这一点(或者我可以做到这一点...啊...)

I think the direct answer to the question is 'No' but I'm hoping that someone has written a real simple library to do this (or I can do it...ugh...)

让我证明我所期待的一个例子。 假如我有以下内容:

Let me demonstrate what I am looking for with an example. Suppose I had the following:

class Person {
  string Name {get; set;}
  int NumberOfCats {get; set;}
  DateTime TimeTheyWillDie {get; set;}
}

我希望能够做这样的事情:

I would like to be able to do something like this:

static void Main() {
  var p1 = new Person() {Name="John", NumberOfCats=0, TimeTheyWillDie=DateTime.Today};
  var p2 = new Person() {Name="Mary", NumberOfCats=50, TimeTheyWIllDie=DateTime.Max};

  var str = String.Format(

"{0:Name} has {0:NumberOfCats} cats and {1:Name} has {1:NumberOfCats} cats.  They will die {0:TimeTheyWillDie} and {1:TimeTheyWillDie} respectively
", p1, p2);

  Console.WriteLine(str);
}

有谁知道如果theres做这样的事情,或者有人的格式写的库去做呢?我知道这不应该太难,但我宁愿没有重新实现轮。

Does anyone know if theres a format for doing something like this or if someone has written a library to do it? I know it shouldn't be too hard, but I'd rather not be reimplementing the wheel.

推荐答案

编辑:您没有实现IFormattable为每个对象......这会是一个皮塔饼,严重限制和一个相当大的维护负担。只要使用反射和ICustomFormatter一个IFormatProvider的,它会与的任意的对象。的String.Format具有过载取的一个作为参数

You don't have to implement IFormattable for each object...that'd be a PITA, severely limiting, and a fairly large maintenance burden. Just use Reflection and a IFormatProvider with ICustomFormatter and it'll work with any object. String.Format has an overload to take one as a parameter.

我从来没有想到过,但你吸引了我 - 所以我不得不给它一个快速旋转。请注意,我选择允许额外的格式字符串,并传递到属性值,而且它只有与非索引以及访问性质的作品(虽然你可以很容易地添加)。

I've never thought of this before, but you intrigued me - so I had to give it a quick whirl. Note that I chose to allow an additional format string to be passed to the property value, and that it only works with non indexed and accessible properties (though you could easily add that).

public class ReflectionFormatProvider : IFormatProvider, ICustomFormatter {
    public object GetFormat(Type formatType) {
        return formatType == typeof(ICustomFormatter) ? this : null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider) {
        string[] formats = (format ?? string.Empty).Split(new char[] { ':' }, 2);
        string propertyName = formats[0].TrimEnd('}');
        string suffix = formats[0].Substring(propertyName.Length);
        string propertyFormat = formats.Length > 1 ? formats[1] : null;

        PropertyInfo pi = arg.GetType().GetProperty(propertyName);
        if (pi == null || pi.GetGetMethod() == null) {
            // Pass thru
            return (arg is IFormattable) ? 
                ((IFormattable)arg).ToString(format, formatProvider) 
                : arg.ToString();
        }

        object value = pi.GetGetMethod().Invoke(arg, null);
        return (propertyFormat == null) ? 
            (value ?? string.Empty).ToString() + suffix
            : string.Format("{0:" + propertyFormat + "}", value);
    }
}

和你略作修改的例子:

var p1 = new Person() {Name="John", NumberOfCats=0, TimeTheyWillDie=DateTime.Today};
var p2 = new Person() {Name="Mary", NumberOfCats=50, TimeTheyWillDie=DateTime.MaxValue};

var str = string.Format(
    new ReflectionFormatProvider(),
    @"{0:Name} has {0:NumberOfCats} cats and {1:Name} has {1:NumberOfCats} cats. 
    They will die {0:TimeTheyWillDie:MM/dd/yyyy} and {1:TimeTheyWillDie} respectively.
    This is a currency: {2:c2}.", 
    p1, 
    p2,
    8.50M
);

Console.WriteLine(str);

输出:

John has 0 cats and Mary has 50 cats. 
They will die 12/10/2008 and 12/31/9999 11:59:59 PM respectively.
This is a currency: $8.50.

这篇关于.NET:是否有插入对象属性的值转换成字符串的String.Format形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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