在静态方法中将List <t>分配给IEnumerable <t>

时间:2017-01-28 13:46:18

标签: c#

我正在尝试在静态方法中将<btn-custom smSize rounded> 分配给<btn-custom smSize="50" rounded="true"> <btn-custom [smSize]="50" [rounded]="true"> 。这是我的代码。

List<T>

我希望IEnumerable<T>的{​​{1}} public class PlayController : Controller { // GET: Play public ActionResult Index() { var a = new a(); b.Test(a.ienuInt); return View(); } } public class a { public IEnumerable<int> ienuInt { get; set; } public a() { ienuInt = new List<int>(); } } public class b { public static void Test(IEnumerable<int> model) { var lists = new List<int>() { 1, 2, 3, 4 }; model = lists; } } 已在ienuInt方法中初始化a。但在lists方法之后,static void Test没有任何内容。其计数为Test表示没有分配任何内容。

有什么问题吗?因为我认为我可以将ienuInt分配给0,因为将lists作为参数传递意味着传递引用而不是值。

你能告诉我如何处理这个问题吗?

1 个答案:

答案 0 :(得分:0)

您目睹的概念是一种通过引用传递的概念&#34; vs.&#34;传递价值&#34;。

将对象传递给Test方法时,该方法中的变量model只是对原始对象的引用。当您将该分配给该方法中的新对象时,您只需更改引用即可。这不会修改原始对象。

举例说明:

public static void Test(SomeObject model)
{
    // Only changes which object in memory "model" points to.
    // The original object outside of this method is unchanged.
    // There are now two objects in memory.
    model = new SomeObject();
}

public static void Test(SomeObject model)
{
    // There's still only one object in memory.
    // The object which was passed to this method sees the change.
    model.SomeProperty = someValue;
}

在您的情况下,您可以做的是返回这个新对象并将其设置为方法之外的变量。所以让方法返回新对象:

public static IEnumerable<int> Test()
{
    return new List<int>() { 1, 2, 3, 4 };
}

然后调用代码将处理更新其变量:

var a = new a();
a.ienuInt = b.Test();

您可以传递a的整个实例并更新该对象的属性。像这样:

public static void Test(a model)
{
    var lists = new List<int>() { 1, 2, 3, 4 };
    model.ienuInt = lists;
}

然后将整个模型传递给方法:

var a = new a();
b.Test(a);

在这种情况下,仍然只有一个a实例,因为在方法中没有创建新实例。该方法只是修改a上的属性。

(旁注:命名你的类和变量只是要求混淆。坚持使用命名约定。例如,调用类A和变量a。)

相关问题