Why I cannot derive from long?
My function returns some long value which contains two values in lower and higher 32 bits.
I thought the best ways to handle return value is to derive my custom type from long and provide type extenders like GetLowerValue(), GetHigherValue().
开发者_开发技巧The problem is that .NET does not allow to derive from long
If you compile that
public class SubmitOrderResult : long
{
}
you get:
cannot derive from sealed type 'long'
Why is that designed so and how can overcome it?
Thanks
As already mentioned value types in .NET are sealed so there is no way you can derive from long. You should create extension methods as suggested.
Example
public static class LongExtensions
{
public static long GetLowerValue(this long value)
{
...
}
public static long GetHigherValue(this long value)
{
...
}
}
You can't derive from any of the .NET Value Types - they are all sealed by definition.
Perhaps you could implement your GetLowerValue and GetHigherValue methods as extension methods?
My function returns some long value which contains two values in lower and higher 32 bits.
That sounds like a really, really dirty hack. It could be appropriate for close-to-metal languages (e.g. C) but not for a higher-level, object-oriented language.
In OO languages, you extend the type system, not harass existing types to do your bidding. Thus, the solution should be to create a new type which carries your information.
What you can do is write a struct with implicit conversion operators. That will work exactly the way you want:
public struct SubmitOrderResult
{
private long _result;
public SubmitOrderResult(long result)
{
_result = result;
}
public long Result
{
get { return _result; }
set { _result = value; }
}
public int GetHigherValue()
{
return (int)(_result >> 32);
}
public int GetLowerValue()
{
return (int)_result;
}
public static implicit operator SubmitOrderResult(long result)
{
return new SubmitOrderResult(result);
}
public static implicit operator long(SubmitOrderResult result)
{
return result._result;
}
}
Then you can do:
SubmitOrderResult result = someObject.TheMethod();
Console.WriteLine(result.GetHigherValue());
Console.WriteLine(result.GetLowerValue());
...just like you wanted.
If I understand correctly, your function actually returns two values, and the fact that you pack them into a long
is an implementation detail. In that case, hide this detail and create a class which contains the value and the required operations:
public class SubmitOrderResult
{
private readonly long value_;
public int OneValue
{
get { return (int)(value_ >> 32); }
}
public int TheOtherValue
{
get { return (int)(value_ & 0xFFFFFFFF); }
}
public SubmitOrderResult(long value)
{ value_ = value; }
}
You can't overcome it.
As long
is a sealed type and therefore you can't inherit from them. See the MSDN
Because structs are implicitly sealed, they cannot be inherited.
For more information, see Inheritance (C# Programming Guide).
精彩评论