简体   繁体   中英

Allow a method to be invoked based on the version of Windows Phone

A method call I want to invoke is only available for Windows Phone 8 and not for the earlier versions, but I want to keep supporting the app for WP8 as well as WP7.1.

I don't mind having a fallback if the device doesn't have WP8.

Is it possible to instruct the app to conditionally invoke the method, and also remove the compile time error.

To achieve something like this on Android (let's say to support pre Froyo devices), what one could do is wrap the piece of code with @TargetApi(Build.VERSION_CODES.FROYO) to avoid the compile time check and before invoking the required method explicitly check for the android version

if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ECLAIR_MR1)

Possible to do something like this on Windows Phone?

+++++++++++++++++

UPDATE: Tried to use reflection but failed so I am describing the exact problem.

Actually, I want to call GetHostNames() from NetworkInformation

Now since the app targets WP7.1 and WP8 I seem to be unable to reference the namespace with

using Windows.Networking.Connectivity;

because the corresponding assembly isn't referenced (I think). I tried, but couldn't find which assembly is this namespace part of.

Without having a working reference to the namespace, my guess is even reflection won't work.

Please excuse me if I am making a beginner mistake, I am new to Windows Phone as well as C# but loving the environment so coming here seeking some knowledge!

To propert support both platforms you should maintain two identical projects, referencing the same code files, but targeting different framework versions. And when doing that, you can then do the following:

Open your application .csproj file, and change the <DefineConstants> element into the following two lines:

<DefineConstants Condition=" $(TargetFrameworkVersion) == 'v7.1' ">DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE;WP7</DefineConstants>
<DefineConstants Condition=" $(TargetFrameworkVersion) == 'v8.0' ">DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE;WP8</DefineConstants>

You'll need to apply this to both the debug and release configurations.

Then wrap your WP8 specific code in a preprocessor directive , like:

#if WP8
    using Windows.Networking.Connectivity;
#endif

Finally the build conditionals can also be applied to assembly reference include statements, example:

<ItemGroup>
    <Reference Include="Microsoft.Advertising.Mobile, Version=6.2.959.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" Condition=" $(TargetFrameworkVersion) == 'v8.0' " />
</ItemGroup>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM