开发者

ASP.NET C# pass object to method

How do I pass an object from one method to another? From the code below, I would like to pass newEvent from xmlReader() to outputData()

public class Event
{
    public int ID {get; set;}
}


public void xmlReader()
{
    Event newEvent = new Event;

    newEvent.ID = 56;

    outputData(newEvent);
}


public void outputDat开发者_如何学Goa(object theEvent)
{
    MainContainerDiv.InnerHtml = theEvent.ID;
}

Thank you, Jordan


You're already passing it, but the only problem you're having is this:

public void outputData(object theEvent)
{
    MainContainerDiv.InnerHtml = ((Event)theEvent).ID;
}

or

public void outputData(Event theEvent)
{
    MainContainerDiv.InnerHtml = theEvent.ID;
}

You have to either cast the object to a particular type (first solution) or set a particular type to your parameter (second solution). It is of course a bigger problem if the same method is called by many different callers. A more robust approach in this case would be to check parameter type:

public void outputData(object theEvent)
{
    if (theEvent is Event)
    {
        MainContainerDiv.InnerHtml = (theEvent as Evenet).ID;
    }
    // process others as necessary
}


change

public void outputData(object theEvent)

to

public void outputData(Event theEvent)


What I think you mean is "how do I turn theEvent from object back into an Event", in which case:

public void outputData(object theEvent)
{
    MainContainerDiv.InnerHtml = ((Event)theEvent).ID;
}

The better option would be to change the method signature for outputData, so that it takes an Event parameter, rather than an object parameter:

public void outputData(Event theEvent)
{
    MainContainerDiv.InnerHtml = theEvent.ID;
}

If, for some reason, you need to pass theEvent as object, but you may need to use it multiple times within outputData, there's a variation on the first method:

public void outputData(object theEvent)
{
    var event = (Event)theEvent;
    MainContainerDiv.InnerHtml = event.ID;
    //
    // You can now use "event" as a strongly typed Event object for any further
    // required lines of code
}


You are passing the object correctly but passing is by up casting....

If the OutputData will only going to accept Object of type events then the defination of the object will b

public void outputData (Event theEvent) {
  ......
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜