【发布时间】:2021-10-08 16:05:45
【问题描述】:
我怎样才能实现这样的目标?
public class BlaBlaBla
{
private PotatoesContainer _containerField;
private bool _booleanField;
private ref T GetBackingFieldRef<T>(string propertyName)
{
if (string.IsNullOrWhiteSpace(propertyName))
throw new ArgumentNullException(nameof(propertyName));
if (propertyName == "BooleanProperty")
return ref _booleanField;
else if (propertyName == "ContainerProperty")
return ref _containerField;
throw new ArgumentException("Property does not exist", nameof(propertyName));
}
public void ManageProperty<T>(string propertyName, T newValue)
{
//Check stuff;
var referenceToField = GetBackingFieldRef<T>(propertyName);
referenceToField = newValue;
}
}
我搜索了所有参考文档,但我看不到任何东西。而且我不能调用(T)。
这可能吗?
还有其他方法吗(Action、Func 之类的)?
【问题讨论】:
-
只为提供的代码,尝试
return ref (T)(object)_booleanField;:它有效吗? -
@OlivierRogier 不,我试过了。
-
@OlivierRogier 我编辑了,添加了一些代码。
-
泛型方法的重点是有一个方法,调用者可以提供他们想要的任何类型并且该方法将正常运行,而不是编写一个调用者需要提供完全正确类型的方法如果他们做任何其他事情,它就会中断。这种方法一开始就不应该是通用的。