简体   繁体   English

C#中的Overload =运算符或在赋值之后和之前触发事件的替代方法?

[英]Overload =operator in C# or alternative ways to trigger a event after and before assignment?

I'm trying to create my own data type. 我正在尝试创建自己的数据类型。
So I started with a base example of Microsoft DynamicDictionary . 所以我开始使用Microsoft DynamicDictionary的基本示例。

The code is : at http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx 代码是: http//msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx

Main part of my type 我的类型的主要部分

public class myDynType : System.Dynamic.DynamicObject
{
    ....
}

Now I want something like this in my code : 现在我在我的代码中想要这样的东西:

[MaxAllowedValue(100)]
myDynType  SomeVar;

As you know we can't overload assignment in C# (= operator) so what are alternative ways to fire a event before assignment and after that ? 如您所知,我们不能在C#(=运算符)中重载赋值,那么在赋值之前和之后触发事件的替代方法是什么?

SomeVar = 7.55;   // I want to fire an event right before assignment
//Plus after assignment 

I want to check the value before assignment to throw an exception if it's bigger than 100. And I want to check it after assignment to round the value or modify it. 我想检查赋值之前的值,如果它大于100则抛出异常。我想在赋值后检查它以舍入值或修改它。

Not exactly, but maybe you can do what you need with properties: 不完全是,但也许你可以用属性做你需要的事情:

myDynType someVar;
[MaxAllowedValue(100)]
myDynType SomeVar
{
    get
    {
        return someVar;
    }
    set
    {
        PreStuff();
        someVar = value;
        PostStuff();
    }
}

You can accomplish this by overloading the implicit conversion (casting) operator. 您可以通过重载隐式转换(强制转换)运算符来实现此目的。 For instance: 例如:

class MyDynType : System.Dynamic.DynamicObject
{
    public int Value { get; set; }
    public static implicit operator MyDynType(int value)
    {
        MyDynType x = new MyDynType();
        if (value > 100)
            x.Value = 100;
        else
            x.Value = value;
        return x;
    }
}

Then you can use it like this: 然后你可以像这样使用它:

dynamic x = (MyDynType)6;
Console.WriteLine(x.Value);  // Outputs "6"
dynamic y = (MyDynType)150;           
Console.WriteLine(y.Value);  // Outputs "100"

For more info, see the MSDN page . 有关详细信息,请参阅MSDN页面 Since you tagged VB.NET, I'll mention that the equivalent in VB.NET is to overload the CType operator using Widening modifier. 既然你标记了VB.NET,我会提到VB.NET中的等价物是使用Widening修饰符重载CType运算符。

However, overloading the conversion operators can cause a lot of confusion, so you should do so sparingly, if at all. 但是,重载转换操作符会导致很多混乱,因此如果有的话,你应该谨慎地这样做。

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

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