简体   繁体   English

在C#中的构造函数上调用方法是一种好方法吗?

[英]Is it a good approach to call a method on a constructor in C#?

I've noticed that I've been doing this a lot (mostly because all my methods are non-static): 我注意到我已经做了很多(主要是因为我所有的方法都是非静态的):

var person = new Person();
var addresses = person.GetAddresses();

A lot of times I just need to call the method once inside my other method. 很多时候,我只需要在其他方法中调用一次该方法即可。 I noticed I can just do this instead: 我注意到我可以这样做:

var addresses = new Person().GetAddresses();

Is there any problems doing it that way? 这样有什么问题吗? It seems like a lot less typing for me. 对于我来说,打字似乎少了很多。 For example, if I wanted to load a model with addresses, I can just do: 例如,如果我想用地址加载模型,我可以这样做:

public ActionResult HelloWorld() {
    var model = new MyModel { Addresses = new Person().GetAddresses() };
    return View(model);
}

What do you guys think? 你们有什么感想?

Btw, my methods are non-static because I'm using a repository. 顺便说一句,我的方法是非静态的,因为我正在使用存储库。 My class is setup something like this: 我的课是这样设置的:

private IMyRepository _myRepository = new MyRepository();

Person () {
    // initialize properties
}

// Constructor for unit testing...
Person (IMyRepository repository) : this() {
   _myRepository = repository;
}

public GetAddresses() {
    return _myRepository.GetAddresses();
}

It's fine to do that, it won't cause any problems. 这样做很好,不会造成任何问题。 Though it is questionable to have a class that's immediately thrown away. 虽然有一个类被立即丢弃是可疑的。 Maybe GetAddresses should be static? 也许GetAddresses应该是静态的?

But in any case, it's perfectly fine to do. 但无论如何,这是完全可以的。

it's ok to do that, but if you want to some jobs just after creating an object of person, you can create an event and raise it in your constructor , then you have your object and some custom data in your own event args in your main class. 这样做是可以的,但是如果您要在创建人对象后立即进行一些工作,则可以创建一个事件并在构造函数中引发它,然后在您自己的主事件中将对象和一些自定义数据包含在自己的事件参数中类。 if it is helpful I can send you a sample code 如果有帮助,我可以给您发送示例代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM