开发者

basic Inheritance in XNA C# [duplicate]

This question already has answers here: Why don't structs support inheritance? 开发者_StackOverflow中文版 (10 answers) Closed 9 years ago.

I'm trying to expand System.TimeSpan in C# because I need a extra method to convert the GameTime to a TimeSpan. This is what i tried:

class TimeSpanner : TimeSpan
{
}

apperently it's not possible to extend the Timespan struct. Does anyone know why it can't be extended? And how do I properly make this work?


You're taking completely the wrong approach. GameTime has member properties ElapsedGameTime and TotalGameTime that provide the two different TimeSpans that make up a GameTime object. Use them like this:

protected override void Update(GameTime gameTime)
{
    TimeSpan elapsed = gameTime.ElapsedGameTime;
    TimeSpan total = gameTime.TotalGameTime;

    // Personally, I just do this:
    float seconds = (float)gameTime.ElapsedGameTime.TotalSeconds;

    // ...
}


You can not inherit from a struct.

Form MSDN on structs:

There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class Object. A struct can implement interfaces, and it does that exactly as classes do.

As an alternative to what you are trying, consider using extension methods.


A TimeSpan is a struct and structs (which are a value type) cannot be subclassed. You should probably investigate using an operator to perform a conversion.

You could do something like this:

public static implicit operator TimeSpan(GameTime gt) 
{
    return gt.GetTimeSpan();
}

You could then use this like this:

TimeSpan timeSpan = (TimeSpan)myGameTime;


If you need an extra method to do a conversion then why not just make an extension method then?

public static void DoStuff(this TimeSpan timeSpan, GameTime gameTime)
{
     ...
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜