转换米公里,格式化视图模型的价值 [英] Convert meters to kilometers and format the value in Viewmodel

查看:114
本文介绍了转换米公里,格式化视图模型的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图模型:

public class PartnerSearchResultVM
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Latitude { get; set; }
    public string Longitude { get; set; }
    public double Distance { get; set; }
    public string Classification { get; set; }
}

我得到这样的数据库中米的距离:2354,58764478263米

I get the distance in meters from the database like this: 2354,58764478263 m

我想present2.35公里

I would like to present 2.35 km

如何改变视图模型,使皈依那里(如果它是做的最好的地方)

How change the Viewmodel to make the convertion there (if it's the best place to do it)

推荐答案

我只读属性添加到您的模型。

I'd add a read-only property to your model.

public double Kilometers { get { return this.Distance / 1000; } }

如果你想有一个格式化字符串后面我会创建第二个只读属性。

If you want a formatted string back I'd create a second readonly property.

public string KilometerDisplay { 
    get { 
        return String.Format("{0:0.00}km", this.Kilometers); 
    } 
}

虽然,这取决于你的使用情况,广义的格式化功能可能是适当的。也许作为一个扩展方法:

Although, depending on your use case, a generalized format function might be appropriate. Perhaps as an extension method:

[Extension]
public string FormatDistance(this double distance) {
    return distance.FormatDistance("");
}

[Extension]
public string FormatDistance(this double distance, string unitString) {
    return return String.Format("{0:0.00}{1}", distance, unitString);
}
// for meters:   result.Distance.FormatDistance("m");
// for kilometers:  result.Kilometers.FormatDistance("km");

然后添加一些XML文档的距离属性解释说这是米。

Then add some XML documentation to the Distance property explaining that it is in meters.

这篇关于转换米公里,格式化视图模型的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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