简体   繁体   中英

How to overload a property setter in C#?

I've decided to use SQLite for some of my new projects. 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. 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):

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:

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#. 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

Sqlite has a NUMERIC type suitable for .NET decimal:

在此处输入图像描述

Or,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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