简体   繁体   English

将函数放在适当的类中

[英]Putting function in appropriate class

public static FirstObjectType GetObject(SecondObjectType secondobjectType) 
{
         do something
}

Where should I put this function? 我应该在哪里放置此功能? Should I put it in SecondObjectType class or FirstObjectType class in terms of code readability, customs and traditions? 就代码可读性,习惯和传统而言,我应该将其放在SecondObjectType类还是FirstObjectType类中? Should the function be included in the return class or the parameter class from your experience? 根据您的经验,该函数应该包含在返回类还是参数类中?

Thanks for your answer. 感谢您的回答。

I usually put the method in the class that has the same type as the return type of the method. 我通常将方法放在与方法的返回类型相同的类中。

eg: 例如:

public static FirstObjectType GetObject(SecondObjectType secondobjectType) 
{
         do something
}

would go in the FirstObjectType class. 将放在FirstObjectType类中。

Alternatively you can use the Factory Pattern and have a factory for getting the objects you need. 另外,您可以使用工厂模式并拥有一个工厂来获取所需的对象。 Which could give you code simliar to the following: 这可以使您的代码类似于以下内容:

FirstObjectTypeFactory.GetObject(SecondObjectType secondObjectType)

Then you always know which factory to get the object from based on its return type. 然后,您总是根据对象的返回类型知道从哪个工厂获取对象。

This is way to vague to answer, but I'll give a few general tips 这是一种模糊的答案,但我会给出一些一般性提示

If you have a collection of FirstObjectTypes and are trying to find the one that matches SecondObjectType , then it belongs to the class that owns the collection. 如果您具有FirstObjectTypes的集合,并尝试查找与SecondObjectType匹配的SecondObjectType ,则它属于拥有该集合的类。 This could be a factory pattern. 这可能是工厂模式。

If you are always creating a new FirstObjectType , it could just be a constructor for FirstObjectType . 如果始终创建一个新的FirstObjectType ,则它可能只是FirstObjectType的构造FirstObjectType

Does SecondObjectType have to have knowledge of FirstObjectType ? SecondObjectType是否必须具有FirstObjectType知识? If so, then it I would consider making it a method on SecondObjectType . 如果是这样,那么我将考虑使其成为SecondObjectType的方法。

There are a million other scenarios and there is no one size fits all. 还有一百万种其他情况,没有一种适合所有情况。

I'll create an Extension Method for that. 我将为此创建一个扩展方法。

Just add this in the signature 只是在签名中添加

public static FirstObjectType GetObject(this SecondObjectType secondobjectType) 
{
    //do something
}

After that you can do: 之后,您可以执行以下操作:

SecondObjectType sobj = new SecondObjectType()
//code
FirstObjectType  fobj = sobj.GetObject();

And put it with my other extension method file like ExtensionMethods.cs. 并将其与我的其他扩展方法文件(如ExtensionMethods.cs)一起放入。 Or if the class containing the GetObject method is static too, put it in the same class (In this case in the SecondObjectType's class) 或者,如果包含GetObject方法的类也是静态的,则将其放在同一类中(在本例中为SecondObjectType的类)

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

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