想請教一下一般public class XXX這樣宣告,然後裏面在寫方法或屬性然後new class後使用
但發現有一個很奇特用法就是在public後用IDbConnection這個介面,然後在設定一個Connection1()方法,之後new Program類別然後使用Connection1()後面可以點出IDbConnection裏面的方法與屬性,這是什麼原理,是繼承嗎,但我沒有下任何繼承,一般public 後面不是都加類別,改介面也行?然後介面下的功能就能被使用?
class Program
{
public IDbConnection Connection1()
{
var Conn = ConfigurationManager.AppSettings["ConnString"];
return new SqlConnection(Conn);
}
static void Main(string[] args)
{
Program program = new Program();
var _cn = program.Connection1().BeginTransaction();
var _cn2 = program.Connection1().ConnectionTimeout;
}
}
namespace System.Data
{
//
// 摘要:
// Represents an open connection to a data source, and is implemented by .NET Framework
// data providers that access relational databases.
public interface IDbConnection : IDisposable
{
//
// 摘要:
// Gets or sets the string used to open a database.
//
// 傳回:
// A string containing connection settings.
string ConnectionString { get; set; }
//
// 摘要:
// Gets the time to wait (in seconds) while trying to establish a connection before
// terminating the attempt and generating an error.
//
// 傳回:
// The time (in seconds) to wait for a connection to open. The default value is
// 15 seconds.
int ConnectionTimeout { get; }
//
// 摘要:
// Gets the name of the current database or the database to be used after a connection
// is opened.
//
// 傳回:
// The name of the current database or the name of the database to be used once
// a connection is open. The default value is an empty string.
string Database { get; }
//
// 摘要:
// Gets the current state of the connection.
//
// 傳回:
// One of the System.Data.ConnectionState values.
ConnectionState State { get; }
//
// 摘要:
// Begins a database transaction.
//
// 傳回:
// An object representing the new transaction.
IDbTransaction BeginTransaction();
//
// 摘要:
// Begins a database transaction with the specified System.Data.IsolationLevel value.
//
// 參數:
// il:
// One of the System.Data.IsolationLevel values.
//
// 傳回:
// An object representing the new transaction.
IDbTransaction BeginTransaction(IsolationLevel il);
//
// 摘要:
// Changes the current database for an open Connection object.
//
// 參數:
// databaseName:
// The name of the database to use in place of the current database.
void ChangeDatabase(string databaseName);
//
// 摘要:
// Closes the connection to the database.
void Close();
//
// 摘要:
// Creates and returns a Command object associated with the connection.
//
// 傳回:
// A Command object associated with the connection.
IDbCommand CreateCommand();
//
// 摘要:
// Opens a database connection with the settings specified by the ConnectionString
// property of the provider-specific Connection object.
void Open();
}
}
public IDbConnection Connection1()
就是你宣告在Program底下的方法
然而他回傳了IDbConnection這個介面的物件
所以你當然能繼續使用他的方法及屬性欄位