Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Конина Анастасия #197

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions ObjectPrinting/IPropertyPrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace ObjectPrinting
{
public interface IPropertyPrintingConfig<TOwner, TPropType>
{
PrintingConfig<TOwner> ParentConfig { get; }
}
}
10 changes: 10 additions & 0 deletions ObjectPrinting/ObjectExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace ObjectPrinting
{
public static class ObjectExtensions
{
public static string PrintToString<T>(this T obj)
{
return ObjectPrinter.For<T>().PrintToString(obj);
}
}
}
118 changes: 88 additions & 30 deletions ObjectPrinting/PrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -1,41 +1,99 @@
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;

namespace ObjectPrinting
{
public class PrintingConfig<TOwner>
{
private readonly HashSet<Type> excludedTypes = new HashSet<Type>();
private readonly HashSet<MemberInfo> excludedMembers = new HashSet<MemberInfo>();

private readonly Dictionary<Type, Func<object, string>> typePrintingRules =
new Dictionary<Type, Func<object, string>>();

private readonly Dictionary<MemberInfo, Func<object, string>> memberPrintingRules =
new Dictionary<MemberInfo, Func<object, string>>();

private readonly Dictionary<Type, CultureInfo> typeCultures = new Dictionary<Type, CultureInfo>();
private readonly Dictionary<MemberInfo, CultureInfo> memberCultures = new Dictionary<MemberInfo, CultureInfo>();

private readonly Dictionary<MemberInfo, Func<string, string>> memberTrimToLength =
new Dictionary<MemberInfo, Func<string, string>>();

private readonly Dictionary<Type, Func<string, string>> typeTrimToLength =
new Dictionary<Type, Func<string, string>>();

private MemberInfo currentMember;

public PropertyPrintingConfig<TOwner, TPropType> Printing<TPropType>()
{
return new PropertyPrintingConfig<TOwner, TPropType>(this);
}

public PropertyPrintingConfig<TOwner, TPropType> Printing<TPropType>(
Expression<Func<TOwner, TPropType>> memberSelector)
{
currentMember = ((MemberExpression) memberSelector.Body).Member;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а что если пользователь сделает так?

            person.PrintToString(config => config.Printing(x => x.Name + 1).SetMaxLength(1));

            person.PrintToString(
                config => config
                    .Printing(x => x.Name[2])
                    .Using(x => ""));

итд

return new PropertyPrintingConfig<TOwner, TPropType>(this);
}

public PrintingConfig<TOwner> Excluding<TPropType>(Expression<Func<TOwner, TPropType>> memberSelector)
{
currentMember = ((MemberExpression) memberSelector.Body).Member;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лишнее

вообще канеш так делать не гуд, эту штука скорее должна вернуть какой то контекст, в котором будут настраивать параметры конкретного поля
хотя исходя из текущей архитектуры класса кажется проблем с этим не будет, но это скорее всего приведет к осложнениям при добавлении новых методов, вообще изменение состояния не оч крутая вещь в "не контрактах", надо постоянно помнить в других методах что надо засетить в поле новое значение, удалить когда нужно, все это приводит к усложнениям

excludedMembers.Add(currentMember);
return this;
}

public PrintingConfig<TOwner> Excluding<TPropType>()
{
excludedTypes.Add(typeof(TPropType));
return this;
}

public void SetPrintingRule<TPropType>(Func<TPropType, string> print)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

вот эта штука сейчас торчит наружу, не оч хорошо, синтаксис твоей либы позволяет написать вот так, и это ничего не дает

ObjectPrinter.For<Person>().SetPrintingRule<int>(x => "int here")

{
if (currentMember == null)
typePrintingRules[typeof(TPropType)] = x => print((TPropType) x);
else
memberPrintingRules[currentMember] = x => print((TPropType) x);
currentMember = null;
}

public void SetCulture<TPropType>(CultureInfo culture)
{
if (currentMember == null)
typeCultures[typeof(TPropType)] = culture;
else
memberCultures[currentMember] = culture;
currentMember = null;
}

public void SetMaxLength<TPropType>(int maxLen)
{
if (currentMember == null)
typeTrimToLength[typeof(TPropType)] = x => x.Substring(0, Math.Min(x.Length, maxLen));

else
memberTrimToLength[currentMember] = x => x.Substring(0, Math.Min(x.Length, maxLen));


currentMember = null;
}

public string PrintToString(TOwner obj)
{
return PrintToString(obj, 0);
}

private string PrintToString(object obj, int nestingLevel)
{
//TODO apply configurations
if (obj == null)
return "null" + Environment.NewLine;

var finalTypes = new[]
{
typeof(int), typeof(double), typeof(float), typeof(string),
typeof(DateTime), typeof(TimeSpan)
};
if (finalTypes.Contains(obj.GetType()))
return obj + Environment.NewLine;

var identation = new string('\t', nestingLevel + 1);
var sb = new StringBuilder();
var type = obj.GetType();
sb.AppendLine(type.Name);
foreach (var propertyInfo in type.GetProperties())
{
sb.Append(identation + propertyInfo.Name + " = " +
PrintToString(propertyInfo.GetValue(obj),
nestingLevel + 1));
}
return sb.ToString();
var serialization = new Serialization(new SerializationConfig(excludedTypes,
excludedMembers,
typePrintingRules,
memberPrintingRules,
typeCultures,
memberCultures,
memberTrimToLength,
typeTrimToLength));
return serialization.Serialize(obj);
}
}
}
22 changes: 22 additions & 0 deletions ObjectPrinting/PropertyPrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;

namespace ObjectPrinting
{
public class PropertyPrintingConfig<TOwner, TPropType> : IPropertyPrintingConfig<TOwner, TPropType>
{
private readonly PrintingConfig<TOwner> printingConfig;

public PropertyPrintingConfig(PrintingConfig<TOwner> printingConfig)
{
this.printingConfig = printingConfig;
}

public PrintingConfig<TOwner> Using(Func<TPropType, string> print)
{
printingConfig.SetPrintingRule(print);
return printingConfig;
}

PrintingConfig<TOwner> IPropertyPrintingConfig<TOwner, TPropType>.ParentConfig => printingConfig;
}
}
31 changes: 31 additions & 0 deletions ObjectPrinting/PropertyPrintingConfigExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Globalization;

namespace ObjectPrinting
{
public static class PropertyPrintingConfigExtensions
{
public static string PrintToString<T>(this T obj, Func<PrintingConfig<T>, PrintingConfig<T>> config)
{
return config(ObjectPrinter.For<T>()).PrintToString(obj);
}

public static PrintingConfig<TOwner> SetMaxLength<TOwner, TPropType>(
this PropertyPrintingConfig<TOwner, TPropType> propConfig, int maxLen)
{
var propertyConfig = ((IPropertyPrintingConfig<TOwner, TPropType>) propConfig).ParentConfig;

propertyConfig.SetMaxLength<TPropType>(maxLen);
return propertyConfig;
}

public static PrintingConfig<TOwner> Using<TOwner, TPropType>(
this PropertyPrintingConfig<TOwner, TPropType> propConfig, CultureInfo culture)
where TPropType : IFormattable
{
var printingConfig = ((IPropertyPrintingConfig<TOwner, TPropType>) propConfig).ParentConfig;
printingConfig.SetCulture<TPropType>(culture);
return printingConfig;
}
}
}
Loading