0

奇怪的问题在这里。我有一个管理一堆事件类的主类......我希望其中一个事件改变主类中的值。

通常,我会通过使用 ref 关键字来做这样的事情......但在这种情况下,我想在构造函数中传递引用,并将类的任何进一步修改反映在主类中。这可能吗?现在我有以下内容:

class MainClass {
     float transparency = 0.0f;

     List<Events> listOfEvents;

     listOfEvents.Add(new FadeInEvent(ref float transparency));
}

class FadeInEvent {
     float transparency;

     public FadeInEvent(ref float t) {
         transparency = t;
     }

     public void Update()  //Occurs every frame
     {
         transparency += 0.01f;
     }
}

这不起作用;FadeInEvent 类不会更新主类中的透明度。我怎样才能解决这个问题?

4

2 回答 2

1

您不能保留对值类型的引用,例如 float。你可以做的是有一个FadeInEvent构造函数,它接受MainClass并修改它的公共 Transparency属性:

class MainClass
{
    float transparency = 0.0f;
    public float Transparency
    {
        get { return transparency;}
        set { transparency = value;}
    }

    List<Events> listOfEvents;
    public void AddFadeInEvent()
    {
        listOfEvents.Add(new FadeInEvent(this));
    }
}

class FadeInEvent
{
    MainClass mainClass;

     public FadeInEvent(MainClass mainClass) 
     {
         this.mainClass = mainClass;
     }

     public void Update()  //Occurs every frame
     {
         mainClass.Transparency += 0.01f;
     }
}
于 2012-10-09T05:30:04.327 回答
1

如何为变量创建一个类,因为类是通过引用自动传递的:

class Transparency
{
    public float Value = 0.0f;
}

class MainClass
{
     Transparency transparency = new Transparency();

     // this List<Events> doesn't match class, but I'm sure this was just a sample of a larger problem
     List<Events> listOfEvents = new List<Events>();

     listOfEvents.Add(new FadeInEvent(transparency));
}

class FadeInEvent{
     Transparency transparency;

     public FadeInEvent(Transparency t) {
         transparency = t;
     }

     public void Update()  //Occurs every frame
     {
         transparency.Value += 0.01f;
     }
}
于 2012-10-09T05:33:42.203 回答