如果 IMarkupExtension 中的给定参数与我期望的类型不兼容,我想在编译期间抛出异常。我能达到这个效果吗?
下面我放了我的实验,但我不知道在哪里以及如何检查我在“TODO”中写的内容
代码(我标记了待办事项)
using System;
using Xamarin.Forms.Xaml;
namespace MySample
{
public class SampleClass : IMarkupExtension
{
public IParameter Parameter { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
return Parameter.GetData();//TODO: throw Exception("Parameter must be of type SampleData1")
}
}
public interface IParameter
{
string GetData();
}
public class SampleData1 : IParameter
{
public string GetData()
{
return "Data1";
}
}
public class SampleData2 : IParameter
{
public string GetData()
{
return "Data2";
}
}
}
XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:mysample="clr-namespace:MySample"
x:Class="MySample.SamplePage">
<ContentPage.Resources>
<mysample:SampleData2 x:Key="SampleData2" />
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout>
<Label>
<Label.Text>
<mysample:SampleClass Parameter="{StaticResource SampleData2}" />
</Label.Text>
</Label>
</StackLayout>
</ContentPage.Content>
</ContentPage>
请注意,参数是 SampleData2 类型,但如果它不是 SampleData1 类型,我想抛出异常。
资源
<mysample:SampleData2 x:Key="SampleData2" />
资源使用
Parameter="{StaticResource SampleData2}"
检查(不一定在这个地方,但肯定在编译期间)
public object ProvideValue(IServiceProvider serviceProvider)
{
return Parameter.GetData();//TODO: throw Exception("Parameter must be of type SampleData1")
}