[英]how to store a reference variable in class c#
我在 Myclass 的構造函數中傳遞了一個類對象(緩存 class 對象)作為引用。
public class Test{
static void Main(string[] args){
Cache<string, string> cache;
Myclass obj = new MyClass(ref cache);
obj.doSomething();
Console.WriteLine(cache.key); // I want this value to get changed according to the doSomething Method
Console.WriteLine(cache.value);// I want this value to get changed according to the doSomething Method
}
}
現在在 MyClass 中,我想設置這個緩存的值
public class Myclass{
ref Cache<string, string> C;
Myclass(ref Cache<string, string> cache){
this.C = cache;
}
void doSomething(){
C.key = "key";
C.value = "value"
}
}
我希望更改 Myclass 中緩存的值應該反映在測試 Class 中。 但我不確定如何實現這一目標。 任何幫助,將不勝感激。
這是我正在嘗試做的完整場景。 我們沒有多個組織,並且該組織的某些屬性對於某些組織是相同的,我們不想一次又一次地計算這些屬性,因為它是昂貴的操作。 該屬性是在上面的 doSomethingMethod 中計算的。
我的緩存實際上是一個列表。 並且這個緩存變量將在多個 orgs 中傳遞。 因此,在 dosomething 方法中,我想檢查緩存是否被任何其他組織設置,如果密鑰存在,我將不會計算操作,我只會從緩存中返回。
如果省略ref
關鍵字,則給構造函數的是對cache
實例的引用。 引用本身將是一個副本,但仍引用同一個實例。 如果您隨后更改所述實例的屬性,它將通過對同一實例的所有其他引用進行反映。
考慮這個例子:
using System;
public class Program
{
public static void Main()
{
MyCache sharedCache = new MyCache();
Department dpt1 = new Department(sharedCache);
Department dpt2 = new Department(sharedCache);
Console.WriteLine($"Dpt1: {dpt1.CacheValue}");
Console.WriteLine($"Dpt2: {dpt2.CacheValue}");
sharedCache.Value = 1;
Console.WriteLine($"Dpt1: {dpt1.CacheValue}");
Console.WriteLine($"Dpt2: {dpt2.CacheValue}");
dpt1.ChangeValue(2);
Console.WriteLine($"Dpt1: {dpt1.CacheValue}");
Console.WriteLine($"Dpt2: {dpt2.CacheValue}");
}
}
public class Department
{
private readonly MyCache cache;
public Department(MyCache cache)
{
this.cache = cache;
}
public int CacheValue => this.cache.Value;
public void ChangeValue(int newValue)
{
this.cache.Value = newValue;
}
}
public class MyCache
{
public int Value {get; set;} = default;
}
Output:
Dpt1: 0 Dpt2: 0 Dpt1: 1 Dpt2: 1 Dpt1: 2 Dpt2: 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.