Method to accept different types

2019-09-04 17:36发布

问题:

Is it possible for a method to accept any type?

For example can I write:

public ActionResult Edit(? vp){

}

where ActionResult would accept an Integer, float, or any other (possibly custom) type?

回答1:

if i understand your meaning so you can use generic like that:

public ActionResult Edit<T>(T vp){ }

T represent the type you want, and whan you call the method give the type in the <>

or you can use object type like this:

public ActionResult Edit(object vp){ }

hope it helped you!



回答2:

You could use object and then write a custom model binder for it by overriding the BindModel method which will decide what value to returned based on the request.

public ActionResult Edit(object vp)
{
     ...
}


回答3:

Your method can accept an object like so:

public ActionResult Edit(object vp)
{
    // you can then cast your object vp to whatever type.
    float x = (float)vp;
}