简体   繁体   English

如何重载 C# 中的属性设置器?

[英]How to overload a property setter in C#?

I've decided to use SQLite for some of my new projects.我决定在我的一些新项目中使用 SQLite。 It seems to be exactly what I want to use, except for the fact that you cant store money as a decimal.这似乎正是我想要使用的,除了你不能将钱存储为小数。 the way that I'm trying to get around this is to store the money values as an INTEGER and then just convert it to a decimal when I retrieve the data in my C# program.我试图解决这个问题的方法是将货币值存储为 INTEGER ,然后当我在 C# 程序中检索数据时将其转换为小数。 My issue is, when I set the price field in my class to the value in the database, an INT value needs to be inputted into the Price property, and converted into decimal (which can be done as shown below):我的问题是,当我将 class 中的价格字段设置为数据库中的值时,需要在 Price 属性中输入一个 INT 值,并将其转换为十进制(可以如下所示进行):

public class ProductModel
{
    private decimal price { get; set; }
    public int Price
    {
        get 
        { 
            // Code
        }
        set { price = (decimal)(value / 100); } 
    }

}

However, elsewhere in my code, I would like to be able to set the value of price by typing the normal decimal format for the money value但是,在我的代码的其他地方,我希望能够通过键入货币值的正常十进制格式来设置价格值

Product.Price = 1.99M

In my head, a very simple way to do this would be to use an 'overloaded property' so that the class can handle the two different input types:在我看来,一个非常简单的方法是使用“重载属性”,以便 class 可以处理两种不同的输入类型:

public class ProductModel
{
    private decimal price { get; set; }
    public int Price
    {
        get 
        { 
            // Code
        }
        set { price = (decimal)(value / 100); } 
    }
    public Decimal Price
    {
        get
        {
            // Code
        }
        set { price = value; }
    }
}

But as I've seen online, overloaded properties do not exist in C#.但正如我在网上看到的,C# 中不存在重载属性。 What would be an alternative to this?有什么替代方法? I could just use two overloaded methods, however that would not be very easy to use with dapper as dapper just saves directly to the class's properties我可以只使用两个重载方法,但是与 dapper 一起使用并不是很容易,因为 dapper 只是直接保存到类的属性中

Sqlite has a NUMERIC type suitable for .NET decimal: Sqlite 有一个适合 .NET 十进制的 NUMERIC 类型:

在此处输入图像描述

Or,或者,

CREATE TABLE [TESTTable] (
  [Id] NUMERIC NOT NULL
, CONSTRAINT [PK_TESTTable] PRIMARY KEY ([Id])
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM