例如:
public static T ConvertUnitMmtoUnitCm<T>(T mmValue)where T:struct
{
dynamic v1 = mmValue;
return (T)(v1 /10);
}
类型转换
Dynamic类型的实例和其他类型的实例间的转换是很简单的,开发人员能够很方便地在dyanmic和非dynamic行为间切换。任何实例都能隐式转换为dynamic类型实例,见下面的例子:
dynamic d1 = 7;
dynamic d2 = “a string”;
dynamic d3 = System.DateTime.Today;
dynamic d4 = System.Diagnostics.Process.GetProcesses();
Conversely, an implicit conversion can be dynamically applied to any expression of type dynamic.
反之亦然,类型为dynamic的任何表达式也能够隐式转换为其他类型。
int i = d1;
string str = d2;
DateTime dt = d3;
例2;
public enum LengthUnitType
{
mm,
cm
}
public class DoubleLenthOfUnit
{
[DataMember]
public double? _value;
public DoubleLenthOfUnit()
{
Set(null, LengthUnitType.mm);
}
public DoubleLenthOfUnit(double? value, LengthUnitType unit)
{
Set(value, unit);
}
public double? Get(LengthUnitType unit,int? precisionNumber = null)
{
if (LengthUnitType.mm == unit)
return _value;
else if (LengthUnitType.cm == unit)
{
if (null == _value)
{
return _value;
}
if (_value * 0.1d >= float.MinValue && _value * 0.1d <= float.MaxValue)
{
if (null == precisionNumber)
{
return _value*0.1d;
}
return Math.Round((double)_value * 0.1d, precisionNumber.Value, MidpointRounding.AwayFromZero);
}
throw new ArithmeticException(
string.Format("DM_LengthUnit:value accuracy lost '{0}'.",
_value));
}
else
{
throw new NotImplementedException(string.Format("DM_LengthUnit: not implement length unit '{0}'.",
unit.ToString()));
}
}
public void Set(double? value, LengthUnitType unit)
{
if (LengthUnitType.mm == unit)
_value = value;
else if (LengthUnitType.cm == unit)
{
if (null != value)
{
if (value * 10 <= float.MaxValue && value * 10 >= float.MinValue)
{
_value = value * 10;
}
else
{
throw new ArithmeticException(
string.Format("DM_LengthUnit:value out of range '{0}'.",
_value));
}
}
}
else
throw new NotImplementedException(string.Format("DM_LengthUnit: not implement length unit '{0}'.", unit.ToString()));
}
}
本文介绍了如何在C#中使用泛型方法实现不同类型之间的除法操作,重点探讨了dynamic类型的转换特性,展示了动态转换为不同类型的示例。
139

被折叠的 条评论
为什么被折叠?



