简体   繁体   English

如果get函数中不存在键/值对,该如何创建?

[英]How to create a key,value pair if it doesn't exist in get function?

I have a get api like the below: 我有一个如下所示的api:

bool GetValue<T>(string key, out T value);

if the value exists, it is returned in value and the function returns true. 如果值存在,则返回value ,函数返回true。 Otherwise, value is set to default(T) and the function returns false. 否则,将value设置为default(T)并且该函数返回false。

Similarly, I have the set api: 类似地,我有set api:

bool SetValue<T>(string key, T value);

Therefore, currently I am using this like: 因此,当前我正在像这样使用:

var exists = GetValue<Details>(@"ProductDetails", out var result);
if (!exists)
{
    _details = new Details();
    SetValue(@"ProductDetails", _details);
}
else
{
    _details = result;
}

I want to create a function that does this in a single line. 我想创建一个在一行中执行此操作的函数。 That is, if the value doesn't already exist it creates a new value with the given arguments and stores that. 也就是说,如果该值尚不存在,它将使用给定的参数创建一个新值并将其存储。

How can I do this ? 我怎样才能做到这一点 ?

private T GetOrCreate<T>(string tableName)
    where T : new()
{
    T result;

    var exists = GetValue<T>(tableName, out result);
    if (!exists)
    {
        result = new T();
        SetValue(tableName, result);
    }

    return result;
}

Should do it, using a generic constraint to make sure a default constructor exists for T . 应该使用通用约束来确保T存在默认构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM