[英]Can you call a class' method when you declare the object?
I have a class, where I declare it, but that class gets added as an item to another bigger class. 我有一个类,我声明它,但该类作为项添加到另一个更大的类。 Is there a way to call the
Init()
method in the same statement as the call? 有没有办法在与调用相同的语句中调用
Init()
方法? Similar to defining public properties/variables when you call the constructor. 与调用构造函数时定义公共属性/变量类似。 I don't want to call the
Init()
method in the constructor because it messes with the WPF Designer. 我不想在构造函数中调用
Init()
方法,因为它与WPF Designer混淆。
FitsView fv = new FitsView();
fv.Init();
You could use a static function to do that: 您可以使用静态函数来执行此操作:
public static FitsView CreateFitsView()
{
var fv = new FitsView();
fv.Init();
return fv;
}
Then you simply call that static function instead of new FitsView()
然后你只需调用静态函数而不是
new FitsView()
You could also try hooking a custom event to your FitsView if it knows when it's ready to be initialized? 您还可以尝试将自定义事件挂接到FitsView,如果它知道何时可以初始化它?
And use it like this: 并像这样使用它:
FitsView fv = new FitsView();
fv.someCustomEvent += (o,e) => { fv.Init(); };
Similar to the StringBuilder.Append
you could alter Init to return a reference to the object. 与
StringBuilder.Append
类似,您可以更改Init以返回对该对象的引用。
Public FitsView Init()
{
//Do stuff
return this;
}
Then: 然后:
FitsView fv = new FitsView().Init();
If the designer gets problematic because of your init method there are two reasons I can think of: 如果设计人员因为你的init方法而出现问题,我可以想到两个原因:
Init
method needs locality of your application (reading resources or files or using hardware) Init
方法中所做的事情需要你的应用程序的位置(读取资源或文件或使用硬件) Init
method needs some external assemblies to be loaded dynamically. Init
方法需要动态加载一些外部程序集。 For the first matter you may want to check: 首先,您可能需要检查:
Also people in here pointed out this bug so please beware (hosting wpf in winforms): https://connect.microsoft.com/VisualStudio/feedback/details/620001/system-componentmodel-designerproperties-getisindesignmode-does-not-work-if-the-wpf-is-hosted-on-a-winform#tabs 此处的人也指出了这个bug,请注意(在winforms中托管wpf): https ://connect.microsoft.com/VisualStudio/feedback/details/620001/system-componentmodel-designerproperties-getisindesignmode-does-not-work- 如果最WPF的是托管式-A-WinForm的#标签
For the second matter you can wrap your Init
method in another let's say InitWrapper
and do your design mode check for wrapper method. 对于第二个问题,你可以将你的
Init
方法包装在另一个假设的InitWrapper
然后检查包装方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.