【问题标题】:C# Method Argument Always Receive as a Value, Not a ReferenceC# 方法参数始终作为值而不是引用接收
【发布时间】:2021-08-30 22:53:46
【问题描述】:

我正在开发 Unity C# 并尝试制作我自己的可序列化字典以与 ScriptableObject 一起使用。我正在使用通用方法和通用索引类来做到这一点。我有一个Add 函数,它接收KeyValue,两者都是任何数据类型,与C#Dictionary 非常相似。我还创建了自己的 KeyValuePair 类来配合它。

但是,每当我将列表作为值传递时,它当然会作为参考接收。但我只想接收一些基于引用的类型和数据类型作为值。在非泛型方法中,我可以在收到它后立即从中创建一个新列表,但显然我不能使用泛型方法来做到这一点。

public bool Add(in S Key, in T Value)
{

    // Apparently I can't do this here:
    
    // T ReceivedValue = new T(Value);

    for (int i = 0; i < KeyValuePairs.Count; i++)
    {
        if (KeyValuePairs[i].Key.Equals(Key))
        {
            Debug.LogError("Key '" + Key + "' already exists in the AMADictionary.");
            return false;
        }
    }

    KeyValuePairs.Add(new AMAKeyValuePair<S, T>(Key, Value));
    return true;
}

为了实现这一点,我总是必须在括号中执行这个过程,同时调用 Add 方法,这很慢,而且总是要记住一件额外的事情。有没有办法在方法中实现这一点?

谢谢大家!

【问题讨论】:

标签: c# unity3d generic-method


【解决方案1】:

一种可能的方法是为类T 使用System.ICloneable 接口。

public class Test<S, T> where T : ICloneable
{
    public void Add(in S key, in T value)
    {
        T ReceivedValue = (T)value.Clone();

        /* ... */
    }
}

在这种情况下,您必须为所有可能的值类型实现Clone 方法。

【讨论】:

  • 如果 OP 想要使用 intbyteboolfloat 等基本值类型,则将无法实现
猜你喜欢
  • 2018-09-28
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-08
相关资源
最近更新 更多