-2

In C# is there a way to make something similar to a struct that is only created when new instances of an object are created? Here is an example. I want people to be able to assign events, the problem is that there are a lot of events to assign, and often they have similar functionality, just for a different object. For example, a left button down event, right button down event, etc. etc. I thought I could organize all these with structs but, I ran into a snag when I found that structs where considered "static" and not able to access non-static members. Is there any sort of structure that would let me do this in C#.

(The end result should let me make a new object, and assign to this objects event through these structures)

MouseObject mouse  = new MouseObject();

mouse.Left.PressedEvent += somemethod();

In this example Left cannot be a struct since it is used in a non-static instance.

4

3 に答える 3

4

Why not use another class?

class MouseButton
{
    public SomeEvent PressedEvent;
}

class MouseObject
{
    public MouseButton Left { get; }
    public MouseButton Right { get; }
}
于 2012-07-07T14:33:59.287 に答える
0

これがあなたが使ったコードだと思います。

public class MouseObject
{
    public struct Left
    {
        public event EventHandler PressedEvent;
    }
}

この場合、LeftはMouseObjectのメンバーではありません。それはただの別のタイプです。この種のカプセル化は、名前空間のように動作します。

あなたがおそらく意図したのは次のようなものでした:

public class MouseObject
{
    public MouseButton Left { get; set; }

    // Left still needs to be intialized, preferably in the constructor
}

public class MouseButton
{
    public event EventHandler PressedEvent;
}
于 2012-07-07T14:39:57.543 に答える
0

Mutable structs are evil. If you make it with structs, as below, it runs, but the PressedEvent never gets my handler, presumably because the struct I'm modifying isn't the one that's really in MouseObject. Go with a class, as in @japreiss's solution.

struct MouseButton
{
    internal void OnPressed()
    {
        if (PressedEvent != null)
            PressedEvent(this, EventArgs.Empty);
    }
    public event EventHandler PressedEvent;
    public event EventHandler ReleasedEvent;
}
class MouseObject
{
    public MouseButton Left { get; private set; }
    public MouseButton Right { get; private set; }
    public void OnLeftPressed()
    {
        Left.OnPressed();
    }
}
static void Main(string[] args)
{
    var m = new MouseObject();
    m.Left.PressedEvent += (s, e) => Console.WriteLine("pressed");
    m.OnLeftPressed();
}

This prints it was null!.

于 2012-07-07T14:36:06.280 に答える