I have the following classes in my solution with the Request
class being allowed to create Response
instances:
public class Request
{
public Guid Id {get;}
public int UserId {get;}
public string SomeInfo {get;}
public Request(Guid id, int userId, string someInfo)
{
Id = id;
UserId = userId;
SomeInfo = someInfo;
}
public Response GetResponse(string content)
{
return new Response(requestId, content);
}
}
public class Response
{
public Guid Id {get;}
public Guid RequestId {get;}
public string Content {get;}
public Response(Guid requestId, string content)
{
Id = Guid.NewGuid();
RequestId = requestId;
Content = content;
}
}
Let's say I remove the GetResponse
method and move its code into an extension method, like this:
public static class RequestExtensions
{
public static Response GetResponse(this Request request, string content)
{
return new Response(request.Id, content);
}
}
Is it an appropriate use of the extension methods? I understand the need of those in the context where you do not have access to the type. But does that make sense to use an extension method on a type I do own?
In my mind (though this question is fairly opinion-based) doing this makes sense in one scenario:
GetResponse
needs to live in a different assembly than Response
for some reason (and there are valid ones) Otherwise you can just use a partial
class if you want the code files separate for some reason.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.