gpt4 book ai didi

c# - 将代码标记为在设计时不运行

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:59:48 24 4
gpt4 key购买 nike

当使用新的 Xamarin.iOS 设计器时,它会自动创建您的 Controller 、 View 等,以便您的 C# 代码运行并实际呈现在设计界面上(而不必等到运行时)。

因此,如果您有一个 Controller ,它的构造函数和 ViewDidLoad 将被调用。

假设我有一个这样的 Controller :

class MyController
{
readonly ISomeService service;

public MyController(IntPtr handle) : base(handle)
{
service = MyIoCContainer.Get<ISomeService>();
}
}

显然在设计时,IoC 容器将完全为空并抛出异常。

有没有办法用 Xamarin.iOS 设计器解决这个问题?也许 #if !DESIGN_TIME 或类似的东西?或者有没有办法让我的 IoC 容器在设计时返回所有对象的模拟实例?

最佳答案

目前推荐的方法是让您的类实现 IComponent 接口(interface)。参见 this doc想要查询更多的信息。所以你的 MyController 类可能看起来像这样:

[Register ("MyController")]
class MyController : UIViewController, IComponent
{
#region IComponent implementation

public ISite Site { get; set; }
public event EventHandler Disposed;

#endregion

readonly ISomeService service;

public MyController(IntPtr handle) : base(handle)
{
}

public override void AwakeFromNib ()
{
if (Site == null || !Site.DesignMode)
service = MyIoCContainer.Get<ISomeService>();
}
}

请注意,Site 在构造函数中始终为 null。从 Storyboard进行初始化的首选位置是 AwakeFromNib 方法。我更新了代码示例以反射(reflect)这一点。

关于c# - 将代码标记为在设计时不运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25827354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com