901225-如何通过引用从方法返回对象? [英] 901225 - how to return an object from a method by reference?
本文介绍了901225-如何通过引用从方法返回对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在以下代码中,如何将查找"从C ++转换为C#?
换句话说,如何在C#中返回对对象的引用?
结构 MyStruct
{
int id;
...
} list [] =
{
...
};
MyStruct& find( int id)
{
for ( int i = 0 ; i< ; _countof(list); i ++)
如果(id == list [i] .id)
返回列表[i];
静态 MyStruct empty = { 0 ,...};
返回为空;
}
解决方案
http: //msdn.microsoft.com/zh-CN/library/14akc2c7.aspx [ http://msdn.microsoft.com/en-us/library/14akc2c7 (v = vs.71).aspx [
或者,可以尝试以下代码
结构 MyStruct { 公共 int ID; 公共 MyStruct( int id){ Id = id; } } var list = 新 List< mystruct>(); // 将项目添加到列表 list.Add(新 MyStruct( 5 )); list.Add(新 MyStruct( 10 )); // 要查找与ID匹配的列表项,请说5使用带有谓词的Find方法 MyStruct foundStruct = list.Find(myStruct = > myStruct.Id == 5 );
in the following code, how do u convert ''find'' from C++ to C#?
in another words, how to return a reference to an object in C#?
struct MyStruct { int id; ... } list[]= { ... }; MyStruct &find(int id) { for (int i=0; i<_countof(list); i++) if (id == list[i].id) return list[i]; static MyStruct empty={0,...}; return empty; }解决方案http://msdn.microsoft.com/en-us/library/14akc2c7.aspx[^]
Use theref
keyword or (out
in your case because you want to (possible) reassign the pointer (when you return the empty struct))
http://msdn.microsoft.com/en-us/library/14akc2c7(v=vs.71).aspx[^]
Btw: I think this pattern is not "state of the art" for .net.
As an alternative, the following code may be tried
struct MyStruct { public int Id; public MyStruct(int id){ Id=id; } } var list = new List<mystruct>(); //add items to the list list.Add(new MyStruct(5)); list.Add(new MyStruct(10)); //To find an item of list matching an Id say 5 use the Find method with a predicate MyStruct foundStruct = list.Find(myStruct => myStruct.Id == 5);
这篇关于901225-如何通过引用从方法返回对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文