[英]How can I get the derived primitive type from a generic interface?
Been struggling with this for a bit so wanted to see if someone here might know the solution.一直在为此苦苦挣扎,所以想看看这里是否有人知道解决方案。 I have a set of interfaces (and an implementation):我有一组接口(和一个实现):
public interface IInputValue
{
}
public interface IInputValue<T> : IInputValue where T : struct
{
T Value { get; set; }
}
public class ButtonInputValue : IInputValue<bool>
{
private bool m_Value;
public bool Value
{
get => m_Value;
set => m_Value = value;
}
}
And then I have a scriptable object class that inherits and uses implementations of IInputValue<T>
.然后我有一个可编写脚本的 object class 继承并使用IInputValue<T>
的实现。
public abstract class InputTrigger : ScriptableObject
{
}
public abstract class InputTrigger<T> : InputTrigger where T : IInputValue
{
public abstract T InputValue { get; }
}
T
for example, could be ButtonInputValue
.例如, T
可以是ButtonInputValue
。 I want to serialize this scriptable object in another class (as InputTrigger
) and simply be able to call .InputValue
on it to get the correct derived type of IInputValue
or just get the primitive value directly through IInputValue<T>.Value
.我想在另一个 class (作为InputTrigger
)中序列化这个可编写脚本的 object 并且只需能够在其上调用.InputValue
以获得正确的派生类型IInputValue
或直接通过IInputValue<T>.Value
获得原始值。 What's the best way to go about doing this? go 关于这样做的最佳方法是什么? Any help is much appreciated.任何帮助深表感谢。
I think you are trying to use interfaces in the wrong way.我认为您正在尝试以错误的方式使用接口。 The purpose of an interface is to abstract common functionality on potentially completely different objects and not caring about the base class that implements the interface.接口的目的是在可能完全不同的对象上抽象通用功能,而不关心实现接口的基本 class。
For instance: You can have a car object and a electric car objects and they can both accelerate and brake.例如:您可以拥有汽车object 和电动汽车对象,它们可以加速和制动。 They do so in different ways but all you need to know is that they can accelerate and brake using the pedals (the interface), without you going to learn to drive a car once again.他们以不同的方式这样做,但您只需要知道他们可以使用踏板(界面)加速和制动,而无需您再次学习驾驶汽车。
To answer your question, I think you can use the interface as a type and call the method on the object, and in case you need to verify it is a certain type that implements that interface you can cast to it.要回答您的问题,我认为您可以将接口用作类型并调用 object 上的方法,如果您需要验证它是实现该接口的特定类型,您可以将其转换为它。
IInputValue<bool> myInputValue;
(ButtonInputValue) myInputValue; // This will be treated as ButtonInputValue because the class implements the IInputValue interface.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.