PDA

View Full Version : افزودن تعدادی متد اورلود به کلاسی که خودمان آنرا ننوشته ایم



mohammadjp
پنج شنبه 19 آبان 1390, 13:22 عصر
چگونه بدون ایجاد مشتق از یک کلاس تعدادی متد به کلاس مزبور اضافه کنم؟

Himalaya
پنج شنبه 19 آبان 1390, 17:17 عصر
سلام
با Extension method

You want to add a method to an existing type (for which
you cannot change the source code)

فرض کنید میخواید برای متد Close از کلاس SqlConnection (که هیچ overload ای نداره) دو تا حالت overload ایجاد کنید (این فقط یه مثاله که روش کار رو نشون میده و هیچ کاربردی نداره)

static class SqlConnectionMethods
{
// 1 overload for close method
public static void Close(this SqlConnection con, int i)
{

}

// 2 overload for close method
public static void Close(this SqlConnection con, string str)
{

}

// define new method for sqlconnection class
public static string NewMethod(this SqlConnection con)
{
return string.Empty;
}
}

نحوه استفاده

var connection = new SqlConnection();
//connection.Close(3);
//connection.NewMethod();