开发者

C#: is it possible to create an object that has a value of its "default property" when referenced?

Is it possible to create an object with a constructor parameter which returns a property value when referenced, without using dot notation? Here's a few examples:

public class myObject
{
    public string myObject {get; private set;}
    public myObject( string tempstring)
    {
        this.myObject = tempstring.ToUpper();
    }
}

var a = new myObject("somevalue");
Console.WriteLine( myObject ); // outputs the string "SOMEVALUE"

Here's another attempt:

public class myInt
{
    public int myInt {get; private set;}
    public myInt(string tempInt)
    {    this.myInt = Convert.ToInt32(tempInt);
    }
}

var a = new myInt("3");
var b = a + a;   // ends up being an int datatype value of 6

I know I could always do var b = a.myInt + a.myInt. I guess I could create a static class with a static function that converts a parameter each time to a result, but it wouldn't maintain state.

Just c开发者_如何学JAVAurious. It would make what I am actually trying to do much less difficult.


In the first case, yes. Override the ToString method.

public class myObject
{
    public string myValue {get; private set;}
    public myObject( string tempstring)
    {
        this.myValue = tempstring.ToUpper();
    }

    public override string ToString()
    {
        return myValue;
    }
}

In the second case, sort of. You shouldn't try to overload operators to offer unexpected behavior. Create a method to perform behavior that wouldn't make sense when reading the code. What you are suggesting (returning an int) would definitely not be expected by me to return an int (mostly because of the var rather than a strictly defined type). Using the + operator to return a new myInt object would make sense. Using the + operator return an int would not.

You could overload the + operator to return a new myInt object, and then also add an implicit cast to int. Just make sure it makes sense, and that it is readable.

Within the class, you could use:

public static implicit operator int(myInt m) 
{
    return myValue;
}

public static myInt operator +(myInt left, myInt right) 
{
    // requires constructor that takes int
    return new myInt(left.myValue + right.myValue);
}

Of course, you could go the direct route, but again only use it when it makes it more readable and not less (note, just like methods operators cannot be overloaded simply by return type, so you'd have to pick between the two).

public static int operator +(myInt left, myInt right) 
{
    return left.myValue + right.myValue;
}


How about implicit conversions. See http://msdn.microsoft.com/en-us/library/z5z9kes2(VS.71).aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜