문제

The context of my question is that I'm using MonoDroid to write a program to consume WCF services. I wanted some of the C# libraries regarding SOAP in C# so MonoDroid was an obvious choice.

I am stuck trying to pass void as template parameter to AsyncTask.

The documentation that Xamarin (developers of MonoDroid) gives on AsyncTask leaves much to be desired and can be found here : http://docs.mono-android.net/?link=C%3aAndroid.OS.AsyncTask

What I need to do, I accomplished in Java with an AsyncTask defined like this

        public class SoapRequestTask extends AsyncTask<Void, Void, String>

What is the C# equivalent of a void template parameter?

도움이 되었습니까?

해결책

I actually found the answer to this for anyone who is interested:

The syntax is

    private class SoapTask : AsyncTask{}

And it works just like AsyncTask in java, but the parameters are all Java.Lang.Objects (with the exception that the parameters type is a Java.Lang.Objects[] ) so you can just set them as needed in the body.

다른 팁

To me, it looks like you don't actually use the void type at all, it's simply used in the example to mean "any type can go here". Reading the AsyncTask's 'generic types paragraph' implies that the 3 types are to represent the parameter type, progress type and result type. so for example, if you created a class declared as:

public class MyStringTask extends AsyncTask<String, Integer, Long> {
...
}

The type of object you pass as the parameter to the execute method would be a string

var myStringTask = new MyStringTask();
myStringTask.execute("the first string", "the second string");

The progress would be notified as an Integer value and the result value would be supplied as a Long.

In C#, you would usually see this declared as:

public abstract class AsyncTask<TParam, TProgress, TResult>

using the 'T' syntax for the type parameters and implemented (using the above example) as:

public class MyStringTask : AsyncTask<string, int, long>
{
    ...
}

In C#, you just can't use void (a.k.a. System.Void) as a generic type parameter. The .Net libraries solve this by having multiple "overloaded" types, like Task and Task<T>.

But I don't know MonoDroid, so there might be some solution specific to it. The documentation seems to suggest there is a special type Java.Lang.Void, that could be used (instead of the normal .Net void that can't be used here).

There is no standard equivalent of Void in C#. The type does exist but it's not available as a generic type argument.

The closest example is F#'s use of Unit as a place holder for slots for which the value is uninteresting. It's easy to replicate in C#

public sealed class Unit { 
  public static Unit Value { get { return null; } }
  public static implicit operator Unit(object source) {
    return Value;
  }
}

It can then be used for values you don't care about

public class SoapRequestTask : AsyncTask<Unit, Unit, String> { 
  ...
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top