Skip to content

Commit 51408bd

Browse files
committed
Fixed Shared.ttinclude and GetUnitAttributeFromUnitClassName() after namespace of attributes had changed.
1 parent 104df0a commit 51408bd

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

Src/UnitsNet/Generated Code/Includes/Shared.ttinclude

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,33 @@
1818
private static UnitAttribute GetUnitAttributeFromUnitClassName(string unitClassName)
1919
{
2020
// Derived UnitAttributes are typically named LengthAttribute, MassAttribute etc.
21-
const string attributeNamespace = "UnitsNet";
21+
const string attributeNamespace = "UnitsNet.Attributes";
2222
string unitAttributeFullName = String.Format("{0}.{1}Attribute", attributeNamespace, unitClassName);
2323
Type unitAttributeType = typeof (Unit).Assembly.GetType(unitAttributeFullName);
2424
if (unitAttributeType == null)
2525
return null;
2626

2727
// Example ctor: public AngleAttribute(double ratio, string pluralName = null)
28-
var attr = (UnitAttribute) Activator.CreateInstance(unitAttributeType, new object[] {0.0, null});
28+
//var attr = (UnitAttribute) Activator.CreateInstance(unitAttributeType, new object[] {0.0, null});
29+
30+
ConstructorInfo simplestCtor = unitAttributeType.GetConstructors().OrderBy(ctor => ctor.GetParameters().Length).First();
31+
object[] parameters = simplestCtor.GetParameters().Select(p => GetDefault(p.ParameterType)).ToArray();
32+
if (parameters.Length == 0)
33+
throw new Exception("Ctor with no params found for type: " + unitAttributeType);
34+
35+
var attr = (UnitAttribute)simplestCtor.Invoke(parameters);
2936
return attr;
3037
}
3138

39+
private static object GetDefault(Type type)
40+
{
41+
if (type.IsValueType)
42+
{
43+
return Activator.CreateInstance(type);
44+
}
45+
return null;
46+
}
47+
3248
private Dictionary<Unit, TUnitAttribute> GetUnitToAttributeDictionary<TUnitAttribute>()
3349
where TUnitAttribute : UnitAttribute
3450
{

0 commit comments

Comments
 (0)