0

如果 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")
}
4

1 回答 1

1

我认为不可能在编译时抛出异常。编译器无法检测到逻辑错误,因此只有在程序执行时才能检测到它们。

编译时错误:

如果我们不遵循任何编程语言的正确语法和语义,那么编译器会抛出编译时错误。

例如:

1.缺少分号

2.关键字大写

3.变量不反抗等

运行时错误:

当程序处于运行状态时会产生运行时错误。它们通常被称为例外。

例如:

1.除以零

2.内存不足

3.取消引用空指针等

您可以使用下面的代码来判断throw a Exception此函数何时触发并且Parameter 不是该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";
        }
于 2018-11-19T07:47:58.460 回答