我正在尝试创建一个公共属性,该属性可以是long
或Guid
。泛型有可能吗?例如像具有两种可能类型的通用属性
public virtual T where T: long or Gui Id { get; set; }
我正在尝试创建一个公共属性,该属性可以是long
或Guid
。泛型有可能吗?例如像具有两种可能类型的通用属性
public virtual T where T: long or Gui Id { get; set; }
是否有可能与仿制药?
这是不可能的,但你可以通过使用implicit operator
同时支持long
和Guid
,示例代码解决:
internal class YourId
{
public long LongId { get; private set; }
public Guid GuidId { get; private set; }
public YourId(long longValue)
{
LongId = longValue;
}
public YourId(Guid guidValue)
{
GuidId = guidValue;
}
public static implicit operator long(YourId yourId)
{
return yourId.LongId;
}
public static implicit operator YourId(long value)
{
return new YourId(value);
}
public static implicit operator Guid(YourId yourId)
{
return yourId.GuidId;
}
public static implicit operator YourId(Guid value)
{
return new YourId(value);
}
}
现在你可以使用:
YourId id1 = Guid.NewGuid();
YourId id2 = long.MaxValue;
不,这是不可能的。如果你只有两种可能的类型,那么只需要写两次类,把尽可能多的通用代码放在一个通用的基类中?
不,这是不可能的。没有这样的限制。这是list of possible constraints。
不,这是不可能的,你必须选择一个相同的父类,或者你应该编写你自己的可以存储两者的类的实现。
喜欢的东西:
class LongOrGuid
{
private Guid _guid;
private long _long;
private bool _isGuid = true;
public LongOrGuid(Guid g)
{
_guid = g;
_isGuid = true;
}
public LongOrGuid(long l)
{
_long = l;
_isGuid = false;
}
public long Long
{
get
{
if(_isGuid)
{
throw new NotSupportedException("This is a guid");
}
return _long;
}
}
public Guid Guid
{
get
{
if(!_isGuid)
{
throw new NotSupportedException("This is a long");
}
return _guid;
}
}
public bool IsGuid
{
get
{
return _isGuid;
}
}
}
一财产不能像那样通用。也许你可以使该类包含通用属性?
您不能限制为long
或Guid
。你可以说:
class ClassContainingYourProperty<T> where T : struct, IFormattable, IComparable<T>, IEquatable<T>
{
static ClassContainingYourProperty() // do type check in static constructor
{
var t = typeof(T);
if (t != typeof(long) && t != typeof(Guid))
throw new NotSupportedException("T cannot be " + t);
}
public virtual T YourProperty { get; set; }
}
这是不可能的。你想达到什么目的?也许我们可以找到解决方案。 –
你可以,但你必须在c#中创建一个联合类型,因为没有提供开箱即用的类型。见http://stackoverflow.com/questions/3151702/discriminated-union-in-c-sharp –