[英]How do I overload the square-bracket operator in C#?
例如,DataGridView允許您執行此操作:
DataGridView dgv = ...;
DataGridViewCell cell = dgv[1,5];
但對於我的生活,我找不到索引/方括號運算符的文檔。 他們怎么稱呼它? 它在哪里實施? 可以扔嗎? 我怎么能在自己的課上做同樣的事情?
ETA:感謝所有快速解答。 簡而言之:相關文件屬於“項目”屬性; 重載的方法是聲明像public object this[int x, int y]{ get{...}; set{...} }
的屬性public object this[int x, int y]{ get{...}; set{...} }
public object this[int x, int y]{ get{...}; set{...} }
; 至少根據文檔,DataGridView的索引器不會拋出。 它沒有提到如果提供無效坐標會發生什么。
再次ETA:好的,即使文檔沒有提到它(頑皮的微軟!),事實證明,如果你為它提供無效的坐標,DataGridView的索引器實際上會拋出一個ArgumentOutOfRangeException。 公平的警告。
這將是項目屬性: http : //msdn.microsoft.com/en-us/library/0ebtbkkc.aspx
也許這樣的事情會起作用:
public T Item[int index, int y]
{
//Then do whatever you need to return/set here.
get; set;
}
Operators Overloadability
+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.
+, -, !, ~, ++, --, true, false All C# unary operators can be overloaded.
==, !=, <, >, <= , >= All relational operators can be overloaded,
but only as pairs.
&&, || They can't be overloaded
() (Conversion operator) They can't be overloaded
+=, -=, *=, /=, %= These compound assignment operators can be
overloaded. But in C#, these operators are
automatically overloaded when the respective
binary operator is overloaded.
=, . , ?:, ->, new, is, as, sizeof These operators can't be overloaded
[ ] Can be overloaded but not always!
對於括號:
public Object this[int index]
{
}
數組索引操作符不能重載 ; 但是,類型可以定義索引器,即帶有一個或多個參數的屬性。 索引器參數用方括號括起來,就像數組索引一樣,但索引器參數可以聲明為任何類型(與數組索引不同,它必須是整數)。
來自MSDN
public class CustomCollection : List<Object>
{
public Object this[int index]
{
// ...
}
}
對於CLI C ++(使用/ clr編譯),請參閱此MSDN鏈接 。
簡而言之,屬性可以命名為“default”:
ref class Class
{
public:
property System::String^ default[int i]
{
System::String^ get(int i) { return "hello world"; }
}
};
如果您使用的是C#6或更高版本,則可以將表達式語法用於get-only索引器:
public object this[int i] => this.InnerList[i];
以下是從內部List對象返回值的示例。 應該給你的想法。
public object this[int index]
{
get { return ( List[index] ); }
set { List[index] = value; }
}
如果你的意思是數組索引器,你只需要通過編寫一個索引器屬性來重載它。你可以重載,(盡可能多地編寫)索引器屬性,只要每個都有不同的參數簽名
public class EmployeeCollection: List<Employee>
{
public Employee this[int employeeId]
{
get
{
foreach(var emp in this)
{
if (emp.EmployeeId == employeeId)
return emp;
}
return null;
}
}
public Employee this[string employeeName]
{
get
{
foreach(var emp in this)
{
if (emp.Name == employeeName)
return emp;
}
return null;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.