[英]How do I use an extension function in another class? C#
I've got a couple of extension functions that I want to transfer between classes. 我有几个扩展函数,我想在类之间转移。
I have a class called Helpers.cs that I want to have the following: 我有一个名为Helpers.cs的类,我想要以下内容:
namespace XYZ
{
public class Helpers
{
public static string Encrypt(this string plainText){
//... do encrypting
}
}
}
In my other class Impliment.cs I want to have the following: 在我的其他课程Impliment.cs中,我想要以下内容:
string s = "attack";
s.Encrypt();
How can I implement this? 我该如何实施?
You're close - extension methods need to be in a static class: 您很接近-扩展方法必须在静态类中:
public static class Helpers
{
public static string Encrypt(this string plainText){
//... do encrypting
}
}
If you tried what you posted you'd get a pretty clear compiler error that says basically the same thing: 如果您尝试了发布的内容,则会得到一个非常清晰的编译器错误,该错误基本上是相同的:
Extension method must be defined in a non-generic static class
扩展方法必须在非通用静态类中定义
Note that your usage will be slightly different that what you want. 请注意,您的用法将与您想要的有所不同。 You can't do:
您不能:
string s = "attack";
s.Encrypt();
becasue strings are immutable. 因为字符串是不可变的。 Best you can do is overwrite the existing varialbe or store the result in a new one:
最好的办法是覆盖现有的变量或将结果存储在新变量中:
string s = "attack";
s = s.Encrypt(); // overwrite
or 要么
string s = "attack";
string s2 = s.Encrypt(); // new variable
You need to make the class
, static
as well and use a using
statement. 您还需要使
class
, static
以及使用using
语句。
Example 例
FileA.cs
: FileA.cs
:
namespace XYZ {
public static class Helpers {
public static string Encrypt(this string plainText){
//... do encrypting
return plainText;
}
}
}
FileB.cs
: FileB.cs
:
using XYZ;
public class MainClass {
public static void Main() {
string s = "input";
s = s.Encrypt();
Console.WriteLine(s);
}
}
To create an Extension Method
, the class
must be static
, but in general it has to follow these rules: 要创建
Extension Method
, class
必须是static
,但通常必须遵循以下规则:
public
and static
public
和static
public
and static
public
且static
this
keyword before the parameter this
关键字的第一个参数 In your case, change the class to be static
, for sample: 在您的情况下,将类更改为
static
,例如:
public static class Helpers
{
public static string Encrypt(this string plainText)
{
//... do encrypting
// return a string;
}
}
I also like to create the classes with name like Type and Extensions
sufix, for sample: StringExtensions.cs
, DateTimeExtensions.cs
, etc. 我还喜欢为示例创建名称如Type和
Extensions
sufix的类: StringExtensions.cs
, DateTimeExtensions.cs
等。
Obs: Remember it is not a type method, it is just a static method, but you use as a method from a type. Obs:请记住,它不是类型方法,它只是静态方法,但是您可以将其用作类型的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.