gpt4 book ai didi

c# - 在 pcl 中创建未初始化的对象

转载 作者:太空宇宙 更新时间:2023-11-03 15:24:32 29 4
gpt4 key购买 nike

有什么方法可以在可移植类库中创建未初始化的对象吗?

在标准 .NET Framework 中,这可以使用 FormatterServices.GetUninitializedObject() 完成.

但是,此类+命名空间在 mscorlib 的 PCL 版本中不可用。有没有我不知道的替代方案?

最佳答案

这个答案是为那些从谷歌来到这里的人准备的,因为他们正在使用 xamarin 来提问:

更新:

如果 pcl 项目设置为 netstandard 2.0,FormatterServices.GetUninitializedObject 将可用。

.Net Api reference

检查它是否与您的运行时兼容:https://github.com/dotnet/standard/blob/master/docs/versions.md#net-standard-versions

没有 .netstandard 库的旧答案:

在 pcl 中的用法:

DependencyService.Get<IObjectFactory>().CreateUninitialized(typeof(MyType));

pcl 定义:

public interface IObjectFactory
{
object CreateUninitialized(Type type);
}

安卓:

[assembly: Xamarin.Forms.Dependency(typeof(ObjectFactory))]
namespace YOURNAMESPACE
{
public class ObjectFactory : IObjectFactory
{
public object CreateUninitialized(Type type)
{
return FormatterServices.GetUninitializedObject(type);
}
}
}

苹果:

[assembly: Xamarin.Forms.Dependency(typeof(ObjectFactory))]
namespace YOURNAMESPACE
{
public class ObjectFactory : IObjectFactory
{
public object CreateUninitialized(Type type)
{
return FormatterServices.GetUninitializedObject(type);
}
}
}

工作人员:

Same method doesnt work here yet. possibly because my project is WP8.1Silverlight. I'll update once i have a reason to change project type and implement it.

关于c# - 在 pcl 中创建未初始化的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35923679/

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