泛型类型的指针? [英] Pointers of generic type?
问题描述
好的,我想创建一个将改变数据类型值的泛型类。我想这样做的原因是我可以撤消和重做方法。我可以为我需要的每个值类型编写一个类。 I.E. double,int ...但是如果我可以创建一个泛型类来做到这一点会容易得多。
这就是我的
class CommandChangeDouble:Command
{
double _previous;
double _new;
double * _objectRef;
public unsafe CommandChangeDouble(double * o,double to)
{
_objectRef = o;
_previous = * o;
_new = to;
* _objectRef = _new;
}
public unsafe void void Undo()
{
* _objectRef = _previous;
}
public unsafe void重做()
{
* _objectRef = _new;
$ / code $ / pre
这就是我想要的
class CommandChangeValue< T> :命令
{
T _previous;
T _new;
T * _objectRef;
public unsafe CommandChangeValue(T * o,T to)
{
_objectRef = o;
_previous = * o;
_new = to;
* _objectRef = _new;
}
public unsafe void void Undo()
{
* _objectRef = _previous;
}
public unsafe void重做()
{
* _objectRef = _new;
$ b 但是这给了我错误ErrorCan not take the地址,获取大小或者声明托管类型的指针('T')
有没有更好的方法来做到这一点或获取方式围绕这个错误?
解决方案不是提供一个指向值的指针,而是提供一个setter:
class CommandChangeValue< T> :命令
{
T _previous;
T _new;
动作< T> _组;
public CommandChangeValue(T值,Action< T> setValue,T newValue)
{
_previous = value;
_new = newValue;
_set = setValue;
setValue(_new);
}
public void Undo(){_set(_previous); }
public void重做(){_set(_new); }
}
// ...
double v = 42;
var c = new CommandChangeValue(v,d => v = d,99);
ok so i want to make a generic class that will change the value of a datatype. The reason i want to do this is so i can have undo and redo methods. I could write a class for each valuetype i need. I.E. double, int... but it would be much easier if i could create a generic class to do this.
This is what i have
class CommandChangeDouble : Command
{
double _previous;
double _new;
double* _objectRef;
public unsafe CommandChangeDouble(double* o, double to)
{
_objectRef = o;
_previous = *o;
_new = to;
*_objectRef = _new;
}
public unsafe void Undo()
{
*_objectRef = _previous;
}
public unsafe void Redo()
{
*_objectRef = _new;
}
}
this is what i want
class CommandChangeValue<T> : Command
{
T _previous;
T _new;
T* _objectRef;
public unsafe CommandChangeValue(T* o, T to)
{
_objectRef = o;
_previous = *o;
_new = to;
*_objectRef = _new;
}
public unsafe void Undo()
{
*_objectRef = _previous;
}
public unsafe void Redo()
{
*_objectRef = _new;
}
}
but this gives me the error Error "Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')"
Is there a better way to do this or a way to get around this error?
解决方案 Instead of supplying a pointer to the value, supply a setter:
class CommandChangeValue<T> : Command
{
T _previous;
T _new;
Action<T> _set;
public CommandChangeValue(T value, Action<T> setValue, T newValue)
{
_previous = value;
_new = newValue;
_set = setValue;
setValue(_new);
}
public void Undo() { _set(_previous); }
public void Redo() { _set(_new); }
}
// ...
double v = 42;
var c = new CommandChangeValue(v, d => v = d, 99);
这篇关于泛型类型的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!