整数

时间:2017-02-03 05:43:33

标签: c# .net implicit-conversion

我创建了一个自定义类来保存从应用程序配置文件中编写的自定义配置中读取的整数值,它完美地处理整数值但是当我将此自定义类值设置为对象类型变量时它有一个问题,它分配整个对象变量而不是它的值。以下是我写的代码。

请帮助我如何只获取对象类型变量中的值而不是自定义整数类的整个对象。

public class IntValueElement : ConfigurationElement
{
    [ConfigurationProperty("value")]
    public int? Value
    {
        get
        {
            int result;
            if (int.TryParse(Convert.ToString(base["value"]), out result))
            {
                return result;
            }
            else
            {
                return null;
            }
        }
    }

    public static implicit operator int?(IntValueElement dt)
    {
        return dt.Value;
    }

    public static implicit operator int(IntValueElement dt)
    {
        if (dt.Value.HasValue)
        {
            return dt.Value.Value;
        }
        else
        {
            return 0;
        }
    }
}

public class CommonConfig : ConfigurationSection
{
    [ConfigurationProperty("companyID")]
    public IntValueElement CompanyID
    {
        get { return (IntValueElement)base["companyID"]; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        StartProcess();
    }

    private static void StartProcess()
    {
        CommonConfig cc = AppConfigReader.GetCommonSettings();

        int compayID = cc.CompanyID;  // perfectly set the company id (an integer value read from app config file) in compayID variable;
        int? compayID2 = cc.CompanyID; // perfectly set the company id (an integer value read from app config file) in compayID2 variable;
        object companyID3 = cc.CompanyID; // here it does not set the company id an integer value in compayID3 variable, instead it set the whole IntValueElement object in companyID3 variable;

    }
}

2 个答案:

答案 0 :(得分:1)

只有在明确施展

时才会有效
object companyID3 = (int?)cc.CompanyID;
object companyID4 = (int)cc.CompanyID;

因为所有类型都派生自object所以在分配基类型时不应用隐式运算符。

  

不允许用户定义到基类的转换。

文档:Using Conversion Operators (C# Programming Guide)

答案 1 :(得分:0)

如果在没有显式强制转换的情况下为完全不同类型的变量赋值,程序将查找适用于目标类型的第一个隐式转换。使用intint?,您的类为这些类型定义隐式转换,因此程序将使用这些转换。

对于object,不需要转换,因为IntValueElement类型(以及其他所有类型)都来自object。在这种情况下,它只是继承,而不是隐式转换,因此程序不会去寻找转换选项。 (顺便说一下,正如Nkosi在他的回答中指出的那样,无法定义从类型到基类型的隐式强制转换。出于这个原因。)

如果您希望程序在分配给object变量时转换值,则必须明确说明:

object companyID3 = (int)cc.CompanyID;
    // OR
object companyID3 = (int?)cc.CompanyID;
相关问题