访问类属性,而不使用点运算符 [英] Accessing a Class property without using dot operator

查看:118
本文介绍了访问类属性,而不使用点运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Double类型调用时,重载一些运营商。要做到这一点,我创建一个类MyDouble,从双继承。 MyDouble看起来有点像这样

I need to overload some operators when called using Double types. To achieve this, I'm creating a class MyDouble, which inherits from Double. MyDouble looks somewhat like this

class MyDouble : Double
{
   Double value;
   // operator overloads go here
}



我要抽象掉了从用户属性,以便它是可用的只是作为一个双。基本上,我希望用户能够做到这一点:

I want to abstract away the value property from the user so that it is usable just as a Double. Basically I want the user to be able to do this:

MyDouble a = 5;         //a.value gets assigned 5
Console.WriteLine(a);   //prints a.value



我不希望用户有专门针对属性。这可能吗? ?我将如何去了解它。

I don't want the user to have to specifically target the value property. Is this possible? How would I go about it?

推荐答案

您可以定义的隐式转换操作符,就像这样:

You can define an implicit conversion operator, like this:

class MyDouble {
    public Value {get; private set;}
    public Double(double value) {
        Value = value;
    }
    // Other declarations go here...
    public static implicit operator double(MyDouble md) {
        return md.Value;
    }
    public static implicit operator MyDouble(double d) {
        return new MyDouble(d);
    }
}

这篇关于访问类属性,而不使用点运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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