简体   繁体   English

C#中相同功能的静态和非静态版本

[英]Static and non-static version of the same function in C#

I have my own implementation of the GetUserId() function made static to be able to retrieve the ID in static context. 我将自己的GetUserId()函数实现为静态,以便能够在静态上下文中检索ID。 But I also have many places where I use standard GetUserId() function built into an asp.net UserManager library. 但是我在很多地方都使用内置在asp.net UserManager库中的标准GetUserId()函数。 My fix for not using different logic for the same thing is overriding the non-static method and using the static one inside it (this is inside the UserManagerService class): 对于不对同一事物使用不同逻辑的解决方法是重写非静态方法,并在其中使用静态方法(这在UserManagerService类内部):

public override string GetUserId(ClaimsPrincipal user)
{
    return GetUserIdStatic(user);
}

public static string GetUserIdStatic(ClaimsPrincipal user)
{
    return user.FindFirst(ClaimTypes.NameIdentifier).Value;
}

I did that because I prefer to call the non-static method in the non-static context (generally it's over 90% of the calls). 我这样做是因为我更喜欢在非静态上下文中调用非静态方法(通常占调用的90%以上)。 So I prefer to call _userManagerService.GetUserId(User) than UserManagerService.GetUserIdStatic(User) whenever I can. 因此,我尽可能地调用_userManagerService.GetUserId(User)不是UserManagerService.GetUserIdStatic(User)

From a readability and maintainability perspective (and eventual harmful consequences that I can't foresee right now) is it better to do it the way described above; 从可读性和可维护性的角度(以及我现在无法预料的最终有害后果)来看,采用上述方法更好。 switch all calls to the static version; 将所有呼叫切换到静态版本; or some other way that I didn't think of? 还是其他我没想到的方式?

Making a static and non-static versions of a method that do the same thing is highly questionable. 制作执行相同操作的方法的静态和非静态版本非常有问题。

You should replace static method to get user id with a static method or a static property to get user manager service. 您应将静态方法替换为静态方法以获取用户ID,或将静态属性替换为静态属性以获取用户管理器服务。 This would let you obtain user id in static context by calling a non-static method: 这样,您可以通过调用非静态方法在静态上下文中获取用户ID:

var userId = StaticGetUserManagerSerice().GetUserIdStatic(user);

or 要么

var userId = UserManagerSerice.Instance.GetUserIdStatic(user);

Firstly it's not clear which class you're putting this static and non-static method in. 首先,不清楚要在哪个类中放入此静态和非静态方法。

It seems your method is what's known as a "pure function", ie it simply returns the same thing regardless of the input and has no side effects. 看来您的方法就是所谓的“纯函数”,即无论输入内容如何,​​它都会简单地返回相同的结果,并且没有副作用。 In this case it doesn't really make sense for the method to be for an instance, as it doesn't deal with the instance's data. 在这种情况下,它并没有真正意义的方法是一个实例,因为它不实例的数据处理。 So from that point of view, calls should be made static. 因此,从该角度来看,应将调用设为静态。

However, in accordance with OOP principals, it seems like the best place for this method would be in the User class, as a non-static method. 但是,按照OOP原则,此方法的最佳位置似乎是作为非静态方法的User类。

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

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