IMarkupExtension-在编译期间检查属性类型(xamarin.forms)
如果IMarkupExtension中的给定参数与我期望的类型不兼容,我希望在编译期间引发异常。 我能达到这个效果吗 下面是我的实验,但我不知道在哪里以及如何检查我在TODO中写的内容 我标记为todo的代码 XAML 不一定要在这里检查,但一定要在编译过程中检查 我认为在编译时抛出异常是不可能的。编译器无法检测到逻辑错误,因此只有在执行程序时才会检测到逻辑错误 编译时错误: 如果我们没有遵循任何编程语言的正确语法和语义,那么编译器就会抛出编译时错误 例如: 1.缺少分号 2.用大写字母书写关键词 3.可变的、不可玷污的等 运行时错误: 当程序处于运行状态时,会生成运行时错误。它们通常被称为例外 例如: 1.除零 2.内存不足 3.取消引用空指针等 当触发此函数且参数不是SampleData1类型时,可以使用下面的代码引发异常IMarkupExtension-在编译期间检查属性类型(xamarin.forms),xamarin.forms,compilation-time,Xamarin.forms,Compilation Time,如果IMarkupExtension中的给定参数与我期望的类型不兼容,我希望在编译期间引发异常。 我能达到这个效果吗 下面是我的实验,但我不知道在哪里以及如何检查我在TODO中写的内容 我标记为todo的代码 XAML 不一定要在这里检查,但一定要在编译过程中检查 我认为在编译时抛出异常是不可能的。编译器无法检测到逻辑错误,因此只有在执行程序时才会检测到逻辑错误 编译时错误: 如果我们没有遵循任何编程语言的正确语法和语义,那么编译器就会抛出编译时错误 例如: 1.缺少分号 2.用大写字母书写关键
是的,你可能是对的。然而,我自欺欺人地认为有人会给出一个令人惊讶的解决方案。感谢您的评论和帮助。
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";
}
}
}
<?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>
<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")
}
public object ProvideValue()
{
if (Parameter is SampleData1)
{
return Parameter.GetData();//TODO: throw Exception("Parameter must be of type SampleData1")
}
else if (Parameter is SampleData2)
{
throw new Exception("Parameter must be of type SampleData1");
}
return "error";
}