开发者

C#,can Extension methods be added to user defined classes in C#(not base classes)

I have a user defined class

publ开发者_C百科ic class Student
{
    int rollno;
    public getrollno()
    {
        return rollno;
    }
}

I want to have extension method checkifRollnoIs1() which will return true or false.

Can I do it & how can I do it?


Here is one way to write one:

public static class StudentExtensions
{
  public static bool checkifRollnoIs1(this Student s)
  {
    return s.getrollno() == 1;
  }
}

By the way - extension methods are not actually added to a class, they just appear that way (intellisense magic).


Yes you can add an extension method.

public static class MyExtensions
{
    public static bool checkifRollnoIs1(this Student student)
    {
        return student.getrollno() == 1;
    }
}

Source

Though if you have access to the source, why do you need an extension method?


You can add extension method for "any" object that could be passed to a Static method for some operation.

For compiler, extension method is nothing more than a static method.

If you have a extension method for "CheckIfRollNoIs1", in that case your call,

studentObj.CheckIfRollNoIs1() 

gets converted to,

StudentExtensions.CheckIfRollNoIs1(studentObj)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜