Skip to content

Commit c4989f2

Browse files
committed
Fix GetAttribute implementation
1 parent daa7528 commit c4989f2

File tree

1 file changed

+11
-16
lines changed

1 file changed

+11
-16
lines changed

UnitsNet/QuantityTypeConverter.cs

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -140,24 +140,19 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT
140140

141141
private static TAttribute? GetAttribute<TAttribute>(ITypeDescriptorContext? context) where TAttribute : UnitAttributeBase
142142
{
143-
if(context is null || context.PropertyDescriptor is null)
144-
return null;
143+
if (context?.PropertyDescriptor is null) return null;
145144

146-
TAttribute? attribute = (TAttribute)context.PropertyDescriptor.Attributes[typeof(TAttribute)];
147-
if (attribute != null)
145+
var attribute = (TAttribute?)context.PropertyDescriptor.Attributes[typeof(TAttribute)];
146+
147+
// Ensure the attribute's unit is compatible with this converter's quantity.
148+
if (attribute?.UnitType != null)
148149
{
149-
QuantityType expected = default(TQuantity).Type;
150-
QuantityType actual = QuantityType.Undefined;
151-
152-
if (attribute.UnitType != null) actual = Quantity.From(1, attribute.UnitType).Type;
153-
if (actual != QuantityType.Undefined && expected != actual)
154-
throw new ArgumentException($"The specified UnitType:'{attribute.UnitType}' dose not match QuantityType:'{expected}'");
155-
156-
//QuantityInfo expected1 = default(TQuantity).QuantityInfo;
157-
//QuantityInfo actual1 = QuantityInfo.
158-
//if (attribute.UnitType != null) actual1 = Quantity.From(1, attribute.UnitType).Info;
159-
//if (actual1 != QuantityType.Undefined && expected1 != actual)
160-
// throw new ArgumentException($"The specified UnitType:'{attribute.UnitType}' dose not match QuantityType:'{expected}'");
150+
string converterQuantityName = default(TQuantity).QuantityInfo.Name;
151+
string attributeQuantityName = Quantity.From(1, attribute.UnitType).QuantityInfo.Name;
152+
if (converterQuantityName != attributeQuantityName)
153+
{
154+
throw new ArgumentException($"The {attribute.GetType()}'s Unittype [{attribute.UnitType}] is not compatible with the converter's quantity [{converterQuantityName}].");
155+
}
161156
}
162157

163158
return attribute;

0 commit comments

Comments
 (0)