为什么将 BeginInit() 与简单的 BitmapImages 一起使用?

发布于 2024-12-18 12:38:24 字数 549 浏览 2 评论 0原文

我在网上看到了很多这样的内容:

var b = new BitmapImage();
b.BeginInit();
b.UriSource = new Uri(myPath, UriKind.RelativeOrAbsolute);
b.EndInit();
myImage.Source = b;

现在,就我而言,我首先会选择更紧凑的版本:

myImage.Source = new BitmapImage(new Uri(myPath, UriKind.RelativeOrAbsolute));

有什么理由让我应该写第一个而不是第二个?

在这种情况下,“BeginInit()”和“EndInit()”到底做了什么,而在第二个版本中不会这样做?

我猜“没什么”,但话又说回来,我有足够的经验向我展示 WPF 比我想象的要微妙得多,所以不要怀疑......

编辑:只是为了澄清,我的观点是并不是说我绝对想节省 4 行代码。我更想知道这两个方法到底是做什么的,以及它们应该(或不应该)被调用的原因。

I have seen a lot of these on the web:

var b = new BitmapImage();
b.BeginInit();
b.UriSource = new Uri(myPath, UriKind.RelativeOrAbsolute);
b.EndInit();
myImage.Source = b;

now, as far as I'm concerned, I would first have gone for the more compact version:

myImage.Source = new BitmapImage(new Uri(myPath, UriKind.RelativeOrAbsolute));

is there any reason why I should write the first one instead of the second one?

what is it exactly that "BeginInit()" and "EndInit()" do in this case, that would not be done in the second version?

I'm guessing "nothing", but then again, I've had enough experience showing me that WPF is a lot more subtle than I would have thought it is to not wonder...

edit: Just to be clear, my point is NOT that I absolutely want to spare 4 lines of code. I'd rather like to know what those two methods do, exactly, and the reason they should (or should not) be called.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

影子是时光的心 2024-12-25 12:38:24

我认为他们这样做只是为了与其他代码保持一致。 BitmapImage 有几个属性,在加载图像之前只需设置一次。例如 DecodePixelHeightDecodePixelWidth
为了正确设置它们,你必须使用BeginInit方式。当然,当有人展示示例时,他们只是使用他们习惯的相同语法,并且只删除不相关属性的行。
如果您不需要设置它们中的任何一个,您可以简化语法。

I think they do this, just to be consistent with other code. BitmapImage have several properties, that have to be set only once before it load the image. For example DecodePixelHeight and DecodePixelWidth.
In order to set them correctly, you have to use BeginInit way. And of course, when someone shows examples, they just use the same syntax they are used to, and only remove lines of unrelated properties.
If you don't need to set any of them, you may brief syntax.

山色无中 2024-12-25 12:38:24

事实上,这两个方法只能成对使用并抛出 InvalidOperationException ,这告诉我它们会停止 BitmapImage 的初始化。这两个方法之间的任何属性初始化都将在 BitmapImage 初始化之前进行。

正如我在评论中所说,

我想这里没有问题,因为你有一个方便的构造函数,它将 Uri 作为参数。

The fact that the two methods can only be used in pairs and throw an InvalidOperationException tells me that they stall the initialization of the BitmapImage. Any property initialization between the two methods will be made before the BitmapImage is initialized.

And as I said in the comment,

I guess there is no problem here because you have a handy constructor which takes the Uri as a parameter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文